Java creating XML and the use of open source dom4j

Source: Internet
Author: User
Tags compact xpath xslt

Java

1 ImportJava.io.File;2 ImportJava.io.StringWriter;3 4 ImportJavax.xml.parsers.DocumentBuilder;5 Importjavax.xml.parsers.DocumentBuilderFactory;6 Importjavax.xml.parsers.ParserConfigurationException;7 ImportJavax.xml.transform.Transformer;8 Importjavax.xml.transform.TransformerConfigurationException;9 Importjavax.xml.transform.TransformerException;Ten Importjavax.xml.transform.TransformerFactory; One ImportJavax.xml.transform.dom.DOMSource; A ImportJavax.xml.transform.stream.StreamResult; -  - Importorg.w3c.dom.Document; the Importorg.w3c.dom.Element; -  -  -  Public classCreatxml { +  -      Public Static voidMain (string[] args) { +         Try { A              at              -             //DOM -Documentbuilderfactory factory =documentbuilderfactory.newinstance (); -Documentbuilder Builder =Factory.newdocumentbuilder (); -Document document =builder.newdocument (); -Element root = document.createelement ("Languages"); inRoot.setattribute ("Cat", "it"); -              toElement lan1 = document.createelement ("LAN"); +Lan1.setattribute ("id", "1"); -Element name1 = document.createelement ("name"); theName1.settextcontent ("Java"); *Element ide1 = document.createelement ("IDE"); $Ide1.settextcontent ("Eclipse");Panax Notoginseng Lan1.appendchild (name1); - Lan1.appendchild (ide1); the              +Element lan2 = document.createelement ("LAN"); ALan2.setattribute ("id", "2"); theElement name2 = document.createelement ("name"); +Name2.settextcontent ("Swift"); -Element Ide2 = document.createelement ("IDE"); $Ide2.settextcontent ("XCode"); $ Lan2.appendchild (name2); - Lan2.appendchild (ide2); -              theElement lan3 = document.createelement ("LAN"); -Lan3.setattribute ("id", "3");WuyiElement Name3 = document.createelement ("name"); theName3.settextcontent ("C #"); -Element ide3 = document.createelement ("IDE"); WuIde3.settextcontent ("Visual Studio"); - Lan3.appendchild (name3); About Lan3.appendchild (IDE3); $              - Root.appendchild (lan1); - Root.appendchild (lan2); - Root.appendchild (LAN3); A Document.appendchild (root); +              the             //------------- -              $Transformerfactory transformerfactory =transformerfactory.newinstance (); theTransformer Transformer =Transformerfactory.newtransformer (); theTransformer.setoutputproperty ("Encoding", "UTF-8"); the              theStringWriter writer =NewStringWriter (); -Transformer.transform (NewDomsource (document),NewStreamresult (writer)); in System.out.println (writer.tostring ()); the              theTransformer.transform (NewDomsource (document),NewStreamresult (NewFile ("Newxml.xml"))); About              the}Catch(parserconfigurationexception e) { the e.printstacktrace (); the}Catch(transformerconfigurationexception e) { + e.printstacktrace (); -}Catch(transformerexception e) { the e.printstacktrace ();Bayi         } the     } the  -}

Use of dom4j

1 Importorg.dom4j.Document;2 Importorg.dom4j.DocumentException;3 ImportOrg.dom4j.DocumentHelper;4 5 6  Public classTest {7 8      Public Static voidMain (string[] args) {9String xmlstring = "<root><people>ACELY</people></root>";Ten          One         Try { A              -              -              theDocument document =Documenthelper.parsetext (xmlstring); -              - System.out.println (Document.asxml ()); -              +              -              +}Catch(documentexception e) { A e.printstacktrace (); at         } -     } -  -}

DOM4J Working with Documents

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 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

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, 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 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 the Zvon tutorial which allows your to learn by Exampl E.

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") C7/>.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 creating XML and the use of open source dom4j

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.