haijiang
2018-07-17 63b87b529196c056fb4d96a58eded3936d3445f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.moral.screen.update;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
import java.util.HashMap;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
/**
 * Created by bin.shen on 6/25/16.
 */
public class ParseXmlService {
 
    public HashMap<String, String> parseXml(String uri) throws Exception {
        HashMap<String, String> hashMap = new HashMap<String, String>();
 
        // 实例化一个文档构建器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // 通过文档构建器工厂获取一个文档构建器
        DocumentBuilder builder = factory.newDocumentBuilder();
        // 通过文档通过文档构建器构建一个文档实例
        Document document = builder.parse(uri);
        //获取XML文件根节点
        Element root = document.getDocumentElement();
        //获得所有子节点
        NodeList childNodes = root.getChildNodes();
        for (int j = 0; j < childNodes.getLength(); j++) {
            //遍历子节点
            Node childNode = (Node) childNodes.item(j);
            if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                Element childElement = (Element) childNode;
                if ("version".equals(childElement.getNodeName())) { //版本号
                    hashMap.put("version",childElement.getFirstChild().getNodeValue());
                } else if (("name".equals(childElement.getNodeName()))) { //软件名称
                    hashMap.put("name",childElement.getFirstChild().getNodeValue());
                } else if (("url".equals(childElement.getNodeName()))) { //下载地址
                    hashMap.put("url",childElement.getFirstChild().getNodeValue());
                } else if (("message".equals(childElement.getNodeName()))) { //消息内容
                    hashMap.put("message",childElement.getFirstChild().getNodeValue());
                }
            }
        }
        return hashMap;
    }
}