现在的位置: 首页 > 综合 > 正文

dom解析非递归方式实现

2018年01月16日 ⁄ 综合 ⁄ 共 2376字 ⁄ 字号 评论关闭

package huawei.com;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class domexample
{
 public domexample()
 {
  DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
  try
  {
   DocumentBuilder dombuilder = domfac.newDocumentBuilder();
   InputStream is = new FileInputStream("E:/library.xml");
   Document doc = dombuilder.parse(is);
   Element root = doc.getDocumentElement();
   NodeList books = root.getChildNodes();
   if(null != books)
   {
    for(int i=0;i<books.getLength();i++)
    {
     Node book = books.item(i);
     if(book.getNodeType() == Node.ELEMENT_NODE)
     {
      for(Node node = book.getFirstChild();node != null;node = node.getNextSibling())
      {
       if(node.getNodeType() == Node.TEXT_NODE && !node.getNodeValue().trim().equals(""))
       {
        String name = node.getNodeValue();
        System.out.println(name);
       }
       else if(node.getNodeType() == Node.ELEMENT_NODE)
       {
        String name = book.getAttributes().getNamedItem("name").getNodeValue();
        System.out.println(name);
        
        for(Node node2 = book.getFirstChild();node2 != null;node2 = node2.getNextSibling())
        {
         if(node2.getNodeType() == Node.ELEMENT_NODE)
         {
          String name2 = node2.getAttributes().getNamedItem("name").getNodeValue();
          System.out.println(name2);
          String name3 = node2.getAttributes().getNamedItem("type").getNodeValue();
          System.out.println(name3);
          for(Node node3 = book.getFirstChild();node3 != null;node3 = node3.getNextSibling())
          {
           if(node3.getNodeType() == Node.ELEMENT_NODE)
           {
            String name4 = node3.getAttributes().getNamedItem("name").getNodeValue();
            System.out.println(name4);
           }
          }
         }
        }
       }
      }
     }
    }
   }
   
  }
  catch(ParserConfigurationException e)
  {
   e.printStackTrace();
  }
  catch(FileNotFoundException e)
  {
   e.printStackTrace();
  }
   catch(SAXException e)
   {
    e.printStackTrace();
   }
   catch(IOException e)
   {
    e.printStackTrace();
   }
 }
 public static void main(String[] args) {
  new domexample();
 }
}

【上篇】
【下篇】

抱歉!评论已关闭.