码迷,mamicode.com
首页 > 其他好文 > 详细

How to parse Xml file -- DOM!

时间:2017-07-10 22:27:04      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:bsp   can   specific   util   string   muti   stat   extc   tag   

We can see that when we want to use the Dom4j to parse XML , we should import org.dom4j.*

At the same time ,that to parse XML by DOM ,we should import org.w3c.dom.*

The conclusion is that DOM and Dom4j is different and located in different jar.The DOM belongs to w3c and the Dom4j belongs to dom4j.

But how do we parse XML by DOM?

  //1.get the DocumentBuilderFactory by its static method

  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

  //2.get the DocumentBuilder by DocumentBuilderFactory‘s newDocumentBuilder() method

  DocumentBuilder builder = factory.newDocumentBuilder();

  //3.get the Document object by DocumentBuilder

  Document document = DocumentBuilder.parse("book.xml");

  //4.to handle the document further ,we can use getElementByTagName("") method get the NodeList

  NodeList list = document.getElementByTagName("");

  //5.get the single specific node

  Node node = list.item(0);

  //6.print the node‘s text content

  System.out.println(node.getTextContent());

 

To improve the effeciency of using DOM to parse XML , write a util is not a bad idea,isn‘t it?

public class DOMUtils{

  public static Document getDocument(String path){

    return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);

  }

  

  public static Document getDocument(File file){

    return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);

  }

 

  public void writeXml2File(Document document,String path){

    TransformerFactory.newInstance().newTransformer.transform(new DOMSource(document),new StreamResult(path));

  }

}

To append an element to a specific element by DOM , we can use these code:

  //1.create an element first

  Element element = document.createElement("element‘s name");

  //2.set the element‘s text content

  element.setTextContent("element‘s content text");

  //3.set the element as the child element and append this child element to the parent element.

  parentElement.appendChild(element);

How to parse Xml file -- DOM!

标签:bsp   can   specific   util   string   muti   stat   extc   tag   

原文地址:http://www.cnblogs.com/ppcoder/p/7147630.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!