It programmer development Essentials-all kinds of resources download list, history of the most IT resources, personal collection summary. Parsing XML
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 indom4j. 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
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 Navigation with XPath
In dom4j XPath expressions can is evaluated on the Document or on any Node in the tree (such as Attribute, Element or Proc essinginstruction). 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 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"); C8/>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 highly recommend Thezvon Tutorial which allows your to learn by example . 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") C9/>.addtext ("James Strachan");
Element Author2 = root.addelement ("author")
. AddAttribute ("name", "Bob")
. AddAttribute ("Location", "US") C13/>.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 is quite straightforward using THEJAXP APIs 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 (); C11/>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;
}
}
See more : http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html