使用org.w3c.dom.*进行XML文件的解析和创建(包括Cdata的解析)

来源:互联网 发布:oppoa203软件下载 编辑:程序博客网 时间:2024/05/16 12:46

最近在项目中使用org.w3c.dom对xml文件进行解析,该包对于较小的xml文件的操作非常简便,推荐大家在使用。

首先,对于org.w3c.dom.*的包,我们不需要额外去进行引用,在jdk1.6自带的rt.jar中就包涵该包。

public viod getXMLNodes(String path){

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            File file = new File(path);//path为文件物理路径
            if (file.isFile()) {
                //dom读取xml文件
                Document document = builder.parse(file);
                //获取android节点集合
                NodeList androidNodeListe= document.getElementsByTagName("android");
                for(int i=0;i<androidNodeListe.getLength();i++){
                    //获取子节点下的值
                    String versionNo = document.getElementsByTagName("versionCode").item(i).getFirstChild().getNodeValue();
                    String versionName = document.getElementsByTagName("versionName").item(i).getFirstChild().getNodeValue();
                }
                NodeList updateLognodeList = document.getElementsByTagName("updateLog");
                int size = updateLognodeList.getLength();
                //获取cdata标志中的内容
                for (int k = 0; k < size; k++) {
                    Node node = updateLognodeList.item(k);
                    NodeList nodes = node.getChildNodes();
                    int size1 = nodes.getLength();
                    for (int i = 0; i < size1; i++) {
                        Node node1 = nodes.item(i);
                        if (node1.getNodeType() == Node.CDATA_SECTION_NODE) {
                            CDATASection cdataNode = (CDATASection) node1;
                            String content = cdataNode.getTextContent();
                        }
                    }
                }
            }

    }


XML文件信息为:

<?xml version="1.0" encoding="UTF-8" ?>
<update>
    <android>
        <versionCode>5</versionCode>
        <versionName>1.1.3</versionName>
        <downloadUrl>xxx
        </downloadUrl>
        <updateLog>
<![CDATA[
test data message!
]]>
        </updateLog>
    </android>
</update>

原创粉丝点击