[XML parsing of dom4j]

dom4j is a Java XML API, an upgrade of jdom, used to read and write XML files. dom4j is a very good JavaXML API with excellent performance, powerful functions and extremely easy-to-use features. Its performance exceeds the official dom technology of sun company, and it is also an open source software, which can be found on SourceForge. You can also find an article on IBM developerWorks that evaluates the performance, functionality and ease of use of the mainstream Java XML API, so you can know that dom4j is excellent in every aspect. Nowadays, we can see that more and more Java software is using dom4j to read and write XML. It is especially worth mentioning that even Sun's JAXM is also using dom4j. This is already a jar package that must be used, and Hibernate also uses it to read and write configuration files.

 

dom4j provides a Java library for working with XML, XPath, and XSLT.

dom4j is an easy to use, open source library for working with XML, XPath, and XSLT on the Java platform, using the Java Collections Framework, and with full support for DOM, SAX, and JAXP.



 

Main features:

designed for the Java platform with full support for the Java Collections Framework (Java 2 Collections)

full support for JAXP, TrAX, SAX, DOM, and XSLT

fully integrated XPath support for easy navigation of XML documents

event based proccessing mode to support for massive documents or XML streams

based on Java interfaces for flexible plug and play implementations.

support for XML Schema Data Type support using Kohsuke Kawaguchis excellent Multi Schema Validator library

 

 

1. Read and parse the XML document: 

code show as below:

SAXReader reader = new SAXReader(); 

Document document = reader.read(new File(fileName)); 

 

Reader's read method is overloaded and can be read from various sources such as InputStream, File, Url, etc. The resulting Document object contains the entire XML. 

The character encoding read is converted according to the encoding defined in the XML file header. If you encounter garbled characters, be careful to keep the encoding names the same everywhere.

 

 

2. Get the Root node

 

Element root=document.getRootElement(); 

The root element is the root node of the xml document. All XML parsing starts with the Root element.

 

3. Traverse the XML tree 

DOM4J provides at least 3 ways to traverse nodes: 

 

   // enumerate all child nodes 

  for ( Iterator i = root.elementIterator(); i.hasNext(); ) { 

  Element element = (Element) i.next(); 

  // do something 

  } 

 

  // enumerate nodes with name foo 

  for ( Iterator i = root.elementIterator(foo); i.hasNext();) { 

  Element foo = (Element) i.next(); 

  // do something 

  } 

 

  // enumerate properties 

  for ( Iterator i = root.attributeIterator(); i.hasNext(); ) { 

  Attribute attribute = (Attribute) i.next(); 

  // do something 

  } 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326308956&siteId=291194637