github地址:https://github.com/Dragonxwl/MyBasePro
1.ParseXmlService
xml文件流解析工具类
public class ParseXmlService {
public HashMap<String, String> parseXml(InputStream inStream)
throws Exception {
HashMap<String, String> hashMap = new HashMap<String, String>();
// 实例化一个文档构建器工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 通过文档构建器工厂获取一个文档构建器
DocumentBuilder builder = factory.newDocumentBuilder();
// 通过文档构建器构建一个文档实例
Document document = builder.parse(inStream);
// 获取XML文件根节点
Element root = document.getDocumentElement();
// 获得子节点
NodeList childNodes = root.getChildNodes();
for (int y = 0; y < childNodes.getLength(); y++) {
if (childNodes.item(y).getNodeType() == Node.ELEMENT_NODE) {
if ("h5CoursewareUrl".equals(childNodes.item(y).getNodeName())) {
String h5CoursewareUrl = childNodes.item(y).getTextContent();
hashMap.put("KJUrl", h5CoursewareUrl);
}
}
}
return hashMap;
}
}
2.在子线程中加载xml文件获取文件流然后解析
Runnable runnable = new Runnable() {
@Override
public void run() {
URL url = null;
try {
url = new URL(TextView_xml.getText().toString());
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5000);
// 把version.xml放到网络上,然后获取文件信息
ParseXmlService service = new ParseXmlService();
InputStream inStream = conn.getInputStream();
final HashMap<String, String> mHashMap = service.parseXml(inStream);
handler.post(new Runnable() {
@Override
public void run() {
TextView_value.setText(mHashMap.get("KJUrl"));
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
3.xml文件内容截图