DOM4J manipulating XML

Source: Internet
Author: User

<?XML version= "1.0" encoding= "GBK"?>  <Persons>    < Men>        < PersonID= "20111907">Pan Teng</ Person>        < PersonID= "20111901">Rei</ Person>    </ Men>    <Women>        < PersonID= "20111908">Yang Yue</ Person>        < PersonID= "20111908">Zhang Dong Month</ Person>    </Women></Persons>
ImportJava.io.*;ImportJava.io.File;ImportJava.io.FileOutputStream; ImportJava.io.FileWriter; Importorg.dom4j.*;ImportOrg.dom4j.io.*;ImportJava.util.*;Importorg.jaxen.*; Public classDom_xml { Public Static voidMain (string[] args) {Try        {//read_xml1 ();//read_xml2 ();//READ_XML3 ();//read_xml4 ();//creatxml ();Modifyxml (); }        Catch(Exception e) {System.out.println ("Error message:" +e); }    }        /*** First way to use iterators to read XML*/     Public Static voidread_xml1 () {Try{Saxreader Reader=NewSaxreader ();//ParserDocument doc = Reader.read (NewFile ("Persons.xml"));//Document ObjectElement root = Doc.getrootelement ();//Get root element <persons>Iterator it = Root.elementiterator ();//<men> <women>             while(It.hasnext ()) {Element ele=(Element) it.next (); Iterator Sec_it=Ele.elementiterator ();  while(Sec_it.hasnext ()) {Element man= (Element) sec_it.next ();//without invoking the next method, you will not move down to create a dead loopString name =Man.getname (); String attr= Man.attributevalue ("id"); String content=Man.gettext (); System.out.println ("Name:" + name + "\nid:" + attr + "\ncontent:" +content); }            }        }        Catch(Exception e) {}}/*** The second way of elements*/     Public Static voidread_xml2 () {Try{Saxreader Reader=NewSaxreader ();//ParserDocument doc = Reader.read (NewFile ("Persons.xml"));//Document ObjectElement root = Doc.getrootelement ();//Get root element <persons>list<element> Listele = root.elements ("Men");//get all the men elements under rootlist<element> listmen = listele.get (0). Elements ("person");//get all the person elements under men              for(Element element_obj:listmen) {String name=Element_obj.getname (); String attr= Element_obj.attributevalue ("id"); String content=Element_obj.gettext (); System.out.println ("Name:" + name + "\nid:" + attr + "\ncontent:" +content); }        }        Catch(Exception e) {}}/*** Third Way to use adapter this is not understood for the time being*/     Public Static voidread_xml3 () {Try{Saxreader Reader=NewSaxreader ();//ParserDocument doc = Reader.read (NewFile ("Persons.xml"));//Document ObjectElement root = Doc.getrootelement ();//Get root element <persons>//The Third Way of adapterDoc.accept (NewVisitorsupport () {//use the child class of the observer to complete the reading of the XML file.                                        Public voidVisit (Element el) {//read the XML using the observation period. System.out.println (El.getname ()+": "+El.gettext ());        }                                     }); }        Catch(Exception e) {}}/*** Fourth Way selectnodes * selectnodes parameter is element path need to learn XPath related knowledge*/     Public Static voidRead_xml4 () {Try{Saxreader Reader=NewSaxreader ();//ParserDocument doc = Reader.read (NewFile ("Persons.xml"));//Document ObjectElement root = Doc.getrootelement ();//Get root element <persons>//fourth reading of XML using SelectNodes//need to import org.jaxen.* package or you will get an errorList List = Doc.selectnodes ("//persons/men/person");//use selectnodes to get the node for the XML you want to query.               for(Object obj:list) {//traverse the node to get the data within the node. Element el =(Element) obj;                  System.out.println (El.gettext ()); }        }        Catch(Exception e) {}}/*** Create XML file * XML file the first line encoding value is UTF-8 this is wrong * Java in the Windows Chinese version of the default is GBK, so you need to manually change*/     Public Static voidCreatxml () {Try{Document Newdoc=documenthelper.createdocument (); Element Persons= Newdoc.addelement ("Persons"); Element Men= Persons.addelement ("Men"); Element Person1= Men.addelement ("Person"); Person1.addattribute ("id", "20111907"); Person1.settext ("Panteng"); Element Person2= Men.addelement ("Person"); Person2.addattribute ("id", "20111901"); Person2.settext ("Leishuai"); File Newxml=NewFile ("Newfile.xml"); if(Newxml.exists ()) {newxml.delete ();    } newxml.createnewfile (); //Create a fileXMLWriter out =NewXMLWriter (NewFileWriter (newxml));            Out.write (Newdoc);            Out.flush ();            Out.close (); System.out.println ("File Creation Complete"); }        Catch(Exception e) {}}/*** Modify XML Delete node, modify Add Property*/     Public Static voidModifyxml () {Try{Saxreader Reader=NewSaxreader ();//ParserDocument doc = Reader.read (NewFile ("Persons.xml"));//Document ObjectElement root = Doc.getrootelement ();//Get root element <persons>Element men = root.element ("Men"); //Delete a Rei record elementIterator it =Men.elementiterator ();  while(It.hasnext ()) {Element ele=(Element) it.next (); if(Ele.gettext (). Equals ("Lei Shuai") {men.remove (ele); }            }            //increase the Wei man recordElement Weinan = men.addelement ("Person"); Weinan.settext ("Wai-Man"); //Modify the ID of the Pan Teng and increase the Age propertyIterator it2 =Men.elementiterator ();  while(It2.hasnext ()) {Element ele=(Element) it2.next (); if(Ele.gettext (). Equals ("Pan Teng") {ele.setattributevalue ("id", "080635"); Ele.addattribute ("Age", "23"); }} File Newxml=NewFile ("Newfile.xml"); if(Newxml.exists ()) {newxml.delete ();    } newxml.createnewfile (); //Create a fileXMLWriter out =NewXMLWriter (NewFileWriter (newxml));            Out.write (DOC);            Out.flush ();            Out.close (); System.out.println ("File Update Complete"); }        Catch(Exception e) {System.out.println ("Error message:" +e); }    }}

It is not difficult to see that the JAVA modification of the XML, actually modifies the Doc object, and then delete the original file, the object is written back to a file, the file name is the same as the original.

DOM4J manipulating 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.