Java-related operations on XML files (dom4j)

Source: Internet
Author: User

1 <?XML version= "1.0" encoding= "UTF-8"?>2 3 < PersonUniversity= "Scau" Location= "GuangZhou">4     <Student>5         <name>Tester1</name>6     </Student>7     <Student>8         <name/>Tester29     </Student>Ten     <Student> One         <inputtype= "text"value= "Fortest"/> A     </Student> -     <Student> -         <name>Hello world!</name> the     </Student> -     <Student> -         <DONTatt1= "Value1"Att2= "value2">Don ' t use the This!!!</DONT> -     </Student> + </ Person>

Above is the contents of the XML file.

Generate the relevant code for the XML file
1      Public voidCreate () {2         //Creating the root node root3Element root = documenthelper.createelement ("Person");4Document document =documenthelper.createdocument (root);5 6         //AddAttribute refers to the creation of attributes within a node7         //: <person university= "Scau" location= "GuangZhou" > where university and location are the attributes of person. 8Root.addattribute ("university", "Scau");9Root.addattribute ("Location", "GuangZhou");Ten  One         //how nodes are created.  A         //and the whole DOM tree is actually extending like this: to think of root as a node, node to add nodes (when you take data, set multiple for loops) -Element e1 = root.addelement ("Student"); -E1.addelement ("name"). AddText ("Tester1")); the  -         //to add nodes in this way, the content is this: <name/>xiangxiao -         //a bit like the HTML <input/> tag.  -         //so, to add nodes in this way, most of them are for the purpose of adding attribute. +Element e2 = root.addelement ("Student"); -E2.addelement ("name"); +E2.addtext ("Tester2"); A  at         //like below, for example . -Element E3 = root.addelement ("Student"); -Element ei = e3.addelement ("Input"); -Ei.addattribute ("type", "text"); -Ei.addattribute ("Value", "Fortest"); -  in         //the next way to add nodes is better understood, -Element e4 = root.addelement ("Student"); toElement ex = e4.addelement ("name"); +Ex.addtext ("Hello world!"); -  the         //Of course, you can also write the following Yiguoduan way: *Element dont_use = root.addelement ("Student"); $Dont_use.addelement ("DONT"). AddAttribute ("Att1", "value1"). AddAttribute ("Att2", "value2"). AddText ("Don ' t use in This!!! ");Panax Notoginseng  -OutputFormat format =NewOutputFormat ("",true);//output format, four spaces plus line, it seems to be the convention commonly known as the bar theFormat.setencoding ("UTF8"); +         Try { AXMLWriter writer =NewXMLWriter (NewFileOutputStream ("Person.xml"), format); the Writer.write (document); + writer.close (); -}Catch(Exception e) { $ e.printstacktrace (); $         } -}

Extracting data from an XML file:

1     /**2 * How to get the node one3 * Although this approach looks simple, another way to better understand some4      */5      Public voidget (String filePath) {6         Try {7File xmlfile =NewFile (filePath);8Saxreader Saxreader =NewSaxreader ();9 TenDocument document =Saxreader.read (xmlfile); One             //Get root node AElement person =document.getrootelement (); -  -             //get the direct child node of the root node the              for(Iterator i =person.elementiterator (); I.hasnext ();) { -                 //<student>...</student> -Element student =(Element) I.next (); -                  for(Iterator j =student.elementiterator (); J.hasnext ();) { +                     //Direct child node of child node:<name>...</name> -Element node =(Element) J.next (); +                     //get the name and content of the node: Name:xiaoxiang ASystem.out.print (Node.getname () + ":" +Node.gettexttrim ()); at                 } - System.out.println (); -             } -}Catch(Exception e) { - e.printstacktrace (); -         } in}
Two:
1     /**2 * How to get nodes two3 * All child nodes are obtained directly from the parent node, and all the properties of the node can be obtained as well4      */5      Public voidAnotherget (String filePath) {6         Try {7File XML =NewFile (filePath);8Saxreader Saxreader =NewSaxreader ();9 TenDocument document =saxreader.read (XML); OneElement person =document.getrootelement (); A  -             //get all properties of a node person -             //Print as a key-value pair theList attrlist =person.attributes (); -System.out.printf ("This is attribute: \ n"); -              for(inti = 0; I < attrlist.size (); i++) { -Attribute item =(Attribute) attrlist.get (i); +System.out.println (Item.getname () + ":" +Item.getvalue ()); -             } +  A             //gets all child nodes of the node person at             //In this specific case, it is <student>, <student> -List nodeList =person.elements (); -System.out.printf ("This is element: \ n"); -              for(inti = 0; I < nodelist.size (); i++) { -Element student =(Element) nodelist.get (i); -                 //get all child nodes of node inList ContentList =student.elements (); -                  for(intj = 0; J < Contentlist.size (); J + +) { toElement Contentnode =(Element) Contentlist.get (j); +System.out.println (Contentnode.getname () + ":" +Contentnode.gettexttrim ()); -                 } the             } *  $             //depending on the structure of the DOM tree, the number of cycles is determined. Panax Notoginseng             //It is generally a two-tier cycle, and of course it may be more, depending on the design at the beginning.  -}Catch(Exception e) { the e.printstacktrace (); +         } A}

Using DOM4J to the basic operation of the XML file is probably so much, anyway, it is just read and write.

Related APIs (looks like it hasn't been updated for a long time): http://www.oschina.net/uploads/doc/dom4j-1.6.1/index.html

References to Maven:

<!--https://mvnrepository.com/artifact/dom4j/dom4j<dependency>   < groupid>dom4j</groupid>   <artifactId>dom4j</artifactId>   <version>1.6.1</ Version></dependency>

In the specific programming, the import into the external package has (because it may overlap with other packages, so incidentally write it):

Import org.dom4j.*;

Import org.dom4j.io*;

The first time to use the blog Park to write code, with the habit of ...

2017.8.7

Java-related operations on XML files (dom4j)

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.