Simple parsing of Java dom4j and application of generating XML

Source: Internet
Author: User

First, dom4j is a Java XML API, is an upgrade of jdom, used to read and write XML files. DOM4J is an excellent javaxml API with performance, power, and ease-of-use features that exceed Sun's official DOM technology and is an open source software that can be found on SourceForge. You can also find an article on IBM developerworks that reviews the performance, functionality, and usability of the mainstream Java XML API, so you know that dom4j is excellent in any way. It is now possible to see more and more Java software using dom4j to read and write XML, especially the JAXM of Sun is dom4j. This is already a jar package that must be used, and hibernate also uses it to read and write configuration files.

Second, the XML parsing process of dom4j

1) Join the dependency package

     <Dependency>      <groupId>org.dom4j</groupId>      <Artifactid>dom4j</Artifactid>      <version>2.1.0</version>    </Dependency>    <Dependency>      <groupId>Com.google.code.gson</groupId>      <Artifactid>Gson</Artifactid>      <version>2.8.2</version>    </Dependency>

Description: The purpose of Gson is to convert the data into JSON form

2) XML template

<Root>    <test1>Test1</test1>    <test1>Test11</test1>    <test2>        <test3>Test3</test3>        <test4>Test4</test4>    </test2>    <test2>        <test3>Test5</test3>        <test4>Test6</test4>    </test2></Root>

3) parsing

ImportCom.google.gson.Gson;ImportCom.google.gson.JsonArray;ImportCom.google.gson.JsonObject;Importorg.dom4j.Document;Importorg.dom4j.Element;ImportOrg.dom4j.io.SAXReader;ImportJava.io.File;Importjava.util.List; Public classDom4jutil { Public Static voidMain (string[] args)throwsException {Saxreader reader=NewSaxreader (); Document Document= Reader.read (NewFile ("D:\\1.xml")); Element Root=document.getrootelement (); Jsonobject Jsonobject=readXml (root); Jsonobject jsonobjectrepetition=readxmlrepetition (root); Gson Gson=NewGson ();        System.out.println (Gson.tojson (jsonobject));    System.out.println (Gson.tojson (jsonobjectrepetition)); }    /*** Dealing with duplicate label data (drawbacks, all data is in the form of arrays, there is a requirement for XML design, otherwise the data is not processed) *@paramRoot *@return     */     Public StaticJsonobject readxmlrepetition (Element root) {//gets all the elements under the nodelist<element> elements =root.elements (); //process data or directly return node data if it exists        if(Elements! =NULL&& elements.size () > 0) {            //declaring a JSON dataJsonobject Jsonobject =NewJsonobject (); //declares a JSON arrayJsonarray mlist =NewJsonarray (); //Traverse all elements             for(Element element:elements) {//read node data until there are no other elements under the nodeJsonobject Jo =readXml (Element);            Mlist.add (Jo); }            //Add JSONJsonobject.add (Root.getname (), mlist); returnJsonobject; } Else{jsonobject Jsonobject=NewJsonobject ();            Jsonobject.addproperty (Root.getname (), Root.gettext ()); returnJsonobject; }    }    /*** Processing of ordinary XML format data, there is no duplicate label (disadvantage, cannot handle duplicate tags under the uniform label) *@paramRoot *@return     */     Public StaticJsonobject readXml (Element root) {//gets all the elements under the nodelist<element> elements =root.elements (); //process data or directly return node data if it exists        if(Elements! =NULL&& elements.size () > 0) {            //declaring a JSON dataJsonobject map =NewJsonobject (); //This is processing all the following data stored in a JSONJsonobject Jo =NewJsonobject ();  for(Element element:elements) {jsonobject m=readXml (Element);            Jo.add (Element.getname (), M.get (Element.getname ()));            } map.add (Root.getname (), Jo); returnmap; } Else{jsonobject Map=NewJsonobject ();            Map.addproperty (Root.getname (), Root.gettext ()); returnmap; }    }}

4) test Results display

{"root": {"test1": "Test11", "test2": {"test3": "Test5", "test4": "Test6"}}}{"root": [{"Test1": "Test1"},{" Test1 ":" Test11 "},{" test2 ": {" test3 ":" Test3 "," test4 ":" Test4 "}},{" test2 ": {" test3 ":" Test5 "," test4 ":" Test6 "}}]}

Three, focus on the explanation

1) The tools written above are basically tools for dealing with specific data.

2) The implementation of the method can also be improved, but I have not found a good data representation, so I wrote two methods

3) can refer to this practice, further to do depth analysis

Iv. creation of XML

 Public Static voidMain (string[] args)throwsException {Document Document=documenthelper.createdocument (); Element Root= Document.addelement ("root"); Element test1= Root.addelement ("Test1"); Test1.addtext ("Test1"); Element test2= Root.addelement ("Test2"); Test2.addtext ("Test2"); OutputStream OutputStream=NewFileOutputStream ("D:\\2.xml"); XMLWriter XMLWriter=NewXMLWriter (OutputStream);        Xmlwriter.write (document);    Xmlwriter.close (); }

Note: Here the XML is created not to say, many times are based on the business.

  

Simple parsing of Java dom4j and application of generating XML

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.