当前位置:编程学习 > C#/ASP.NET >>

sax方式XML文件解析之DOM方法

 代码如下 复制代码
<?xml version="1.0" encoding="utf-8"?>
<Students>
    <student id="1">
        <name>杨振宇</name>   
        <sno>2008011123</sno>
        <易做图>男</易做图>
        <phone>18618405551</phone>
    </student>
    <student id="2">
        <name>张瑞</name>   
        <sno>2008011122</sno>
        <易做图>男</易做图>
        <phone>15120058124</phone>
    </student>
    <student id="3">
        <name>陈明</name>   
        <sno>2008011121</sno>
        <易做图>男</易做图>
        <phone>15801281851</phone>
    </student>
    <student id="4">
        <name>苏玉杰</name>   
        <sno>2008011120</sno>
        <易做图>男</易做图>
        <phone>18618405551</phone>
    </student>
    <student id="5">
        <name>高阳</name>   
        <sno>2008011145</sno>
        <易做图>女</易做图>
        <phone>18618405590</phone>
    </student>
</Students>

 
可以用一下的方式进行解析:
 

 代码如下 复制代码
public static void parse(File file) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(file);
        Element root = doc.getDocumentElement();
        NodeList childList = root.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            Node child = childList.item(i);
            if (child instanceof Element) {
                Element element = (Element) child;
                NodeList childInfo = element.getChildNodes();
                for (int j = 0; j < childInfo.getLength(); j++) {
                    Node node = childInfo.item(j);
                    if (node instanceof Element) {
                        Element e = (Element) node;
                        Log.v("tag", "" + e.getTagName());
                        Text textNode = (Text) e.getFirstChild();
                        String text = textNode.getData().trim();
                        if (e.getTagName().equals("name"))
                            Log.v("tag", "" + text);
                        else if (e.getTagName().equals("sno"))
                            Log.v("tag", "" + text);
                        else if (e.getTagName().equals("易做图"))
                            Log.v("tag", "" + text);
                        else if (e.getTagName().equals("phone"))
                            Log.v("tag", "" + text);
                    }
                }
 
            }
        }
    }
补充:asp.net教程,.Net开发
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,