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

作者:袖梨 2022-06-25
 代码如下 复制代码


   
        杨振宇   
        2008011123
       
        18618405551
   

   
        张瑞   
        2008011122
       
        15120058124
   

   
        陈明   
        2008011121
       
        15801281851
   

   
        苏玉杰   
        2008011120
       
        18618405551
   

   
        高阳   
        2008011145
       
        18618405590
   


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

 代码如下 复制代码
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("sex"))
                            Log.v("tag", "" + text);
                        else if (e.getTagName().equals("phone"))
                            Log.v("tag", "" + text);
                    }
                }
 
            }
        }
    }

相关文章

精彩推荐