Java parsing XML Guide using dom4j
The beautiful Life of the Sun Vulcan (http://blog.csdn.net/opengl_es)
This article follows "Attribution-non-commercial use-consistent" authoring public agreement
Reprint Please keep this sentence: Sun Vulcan's Beautiful Life-this blog focuses on Agile development and mobile and IoT device research: IOS, Android, HTML5, Arduino, Pcduino , Otherwise, the article from this blog refused to reprint or re-reproduced, thank you for your cooperation.
Parsing XML
Parsing XML
One of the first things to do is to parse an XML document of some kind. It's easy to do this in dom4j. The following code demonstrates how to do this.
One of the first things you'll probably want to does is to parse an XML document of some kind. This is an easy-to-do in dom4j. The following code demonstrates.
Import Java.net.url;import org.dom4j.document;import org.dom4j.documentexception;import org.dom4j.io.SAXReader; public class Foo {public Document parse (url url) throws documentexception { Saxreader reader = new Saxreader ();
document Document = reader.read (URL); return document; }}
Using iterators
Using iterators
An XML document can be navigated using a variety of methods to return to a standard Java iterator. For example:
A document can be navigated using a variety of methods and return standard Java iterators. For example
public void Bar (document document) throws Documentexception { Element root = Document.getrootelement (); Iterate through child elements of the root for (Iterator i = Root.elementiterator (); I.hasnext ();) { Element element = (Element) i.next (); Do something } //Iterate through child elements of the root with element name ' foo ' for (Iterator i = Root.el Ementiterator ("foo"); I.hasnext (); { element foo = (element) i.next (); Do something } //Iterate through attributes of the root for (Iterator i = Root.attributeiterator (); i.hasn Ext (); ) { Attribute Attribute = (Attribute) i.next (); Do something } }
Powerful XPath Navigation
Powerful Navigation with XPath
An XPath expression in dom4j can be applied to a document or to any node in that tree (such as attributes, elements, or processing indicators). This allows for complex navigation throughout the document using a single line of code. For example:
In dom4j XPath Expressions can is evaluated on the Document or on any Node in the tree (such as Attribute, Elemen T or ProcessingInstruction). This is allows complex navigation throughout the document with a single line of code. For example.
public void Bar (document document) { List list = Document.selectnodes ("//foo/bar"); Node node = document.selectsinglenode ("//foo/bar/author"); String name = node.valueof ("@name"); }
For example, if you want to find all the hypertext links found in an XHTML document, the following code will be used:
For example if your wish to find all the hypertext links in a XHTML document the following code would do the trick.
public void FindLinks (document document) throws Documentexception { List list = Document.selectnodes ("//a/@href"); C2/>for (Iterator iter = List.iterator (); Iter.hasnext ();) { Attribute Attribute = (Attribute) iter.next (); String URL = attribute.getvalue (); } }
If you need any help learning the XPath language, we strongly recommend Zvon tutorial, which allows you to learn by example.
If you need any help learning the XPath language we highly recommend the Zvon tutorial which allows your to learn by Exampl E.
Fast Cycle
Fast Looping
If you ever has to walk a large XML document tree then for performance we recommend you use the fast looping method which Avoids the cost of creating a Iterator object for Each loop. For example
public void Treewalk (document document) { Treewalk (document.getrootelement ()); } public void Treewalk (element Element) { for (int i = 0, size = Element.nodecount (); i < size; i++) { Node nod E = Element.node (i); if (node instanceof Element) { Treewalk (Element) node); } else { //do Something ...}}}
Creating a new XML document
Often in dom4j you'll need to create a new document from scratch. Here's an example of doing.
Import Org.dom4j.document;import Org.dom4j.documenthelper;import Org.dom4j.element;public class Foo {public Document CreateDocument () { Document document = Documenthelper.createdocument (); Element root = document.addelement ("root"); Element Author1 = root.addelement ("author") . AddAttribute ("name", "James") . AddAttribute ("Location", "UK") C6/>.addtext ("James Strachan"); Element Author2 = root.addelement ("author") . AddAttribute ("name", "Bob") . AddAttribute ("Location", "US")
.addtext ("Bob mcwhirter"); return document; }}
Writing a document to a file
A quick and easy-to-write a Document (or any Node) to a Writer is via the Write () method.
FileWriter out = new FileWriter ("Foo.xml"); document.write (out);
If you want to is able to change the format of the output, such as pretty printing or a compact format, or you want to be Able to work with Writer objects or OutputStream objects as the destination and then you can use the XMLWriter class.
Import Org.dom4j.document;import Org.dom4j.io.outputformat;import Org.dom4j.io.xmlwriter;public class Foo { public void Write (document document) throws IOException { //lets write to a file XMLWriter writer = new XMLWriter ( new FileWriter ("Output.xml") ); Writer.write (document); Writer.close (); Pretty print the document to System.out outputformat format = Outputformat.createprettyprint (); writer = new XMLWriter (system.out, format); Writer.write (document); Compact format to system.out format = Outputformat.createcompactformat (); writer = new XMLWriter (system.out, format); Writer.write (document);} }
converting to and from Strings
If you had a reference to a Document or any other Node such as an Attribute or Element, you can turn it into the default XML text via the Asxml () method.
Document document = ...; String text = Document.asxml ();
If you had some XML as a String you can parse it back into a Document again using the helper method Documenthelper.parset EXT ()
String Text = "<person> <name>James</name> </person>"; Document document = Documenthelper.parsetext (text);
Styling a Document with XSLT
Applying XSLT on a Document are quite straightforward using the JAXP API from Sun. This allows the against any XSLT engine such as Xalan or SAXON. Here's an example of using JAXP to create a transformer and then applying it to a Document.
Import Javax.xml.transform.transformer;import Javax.xml.transform.transformerfactory;import org.dom4j.Document; Import Org.dom4j.io.documentresult;import Org.dom4j.io.documentsource;public class Foo {public Document Styledocument ( document document, String stylesheet ) throws Exception { //load the transformer using JAXP Transformerfactory factory = Transformerfactory.newinstance (); Transformer Transformer = Factory.newtransformer ( new Streamsource (stylesheet) ); Now lets style the given document DocumentSource Source = new DocumentSource (document); Documentresult result = new Documentresult (); Transformer.transform (source, result); Return the transformed document document Transformeddoc = Result.getdocument (); return transformeddoc;} }
Java parsing XML Guide using dom4j