Java Starts from scratch 43 (dom4j parsing XML)

Source: Internet
Author: User

First, create XML
//Build XML     Public Static voidGernatorxml () {//Create Document ObjectDocument doc =documenthelper.createdocument (); //creating the root node studentsElement studentselement = doc.addelement ("Students"); //Creating child nodes studentElement studentElement1 = studentselement.addelement ("Student"); //Add id attributeStudentelement1.addattribute ("id", "1001"); //Add child nodesStudentelement1.addelement ("name"). SetText ("Zhang San")); Studentelement1.addelement ("Age"). SetText ("18"); Studentelement1.addelement ("Sex"). SetText ("male")); Studentelement1.addelement ("Phone"). SetText ("13800138000")); Studentelement1.addelement ("Address"). SetText ("Shenzhen Baoan"); //Create the same 2 student nodes againElement StudentElement2 = studentselement.addelement ("Student"); //Add id attributeStudentelement2.addattribute ("id", "10012"); //Add child nodesStudentelement2.addelement ("name"). SetText ("John Doe")); Studentelement2.addelement ("Age"). SetText ("19"); Studentelement2.addelement ("Sex"). SetText ("female")); Studentelement2.addelement ("Phone"). SetText ("13412369854")); Studentelement2.addelement ("Address"). SetText ("Shanghai")); //Create the same 2 student nodes againElement StudentElement3 = studentselement.addelement ("Student"); //Add id attributeStudentelement3.addattribute ("id", "10013"); //Add child nodesStudentelement3.addelement ("name"). SetText ("Harry")); Studentelement3.addelement ("Age"). SetText ("25"); Studentelement3.addelement ("Sex"). SetText ("female")); Studentelement3.addelement ("Phone"). SetText ("13410110104")); Studentelement3.addelement ("Address"). SetText ("Guangdong")); Try {            //Create XML writes document to XML//Set FormatOutputFormat format =Outputformat.createprettyprint (); //set character encoding can also be set to gb2312 or GBKFormat.setencoding ("Utf-8"); //inputXMLWriter writer =NewXMLWriter (NewFileWriter ("Xml/students.xml"), format); //Writing DocumentsWriter.write (DOC); //Close the streamWriter.close (); //Output HintsSystem.out.println ("====== Write succeeded ======="); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }

Second, parsing XML
    //Read XML     Public Static voidGetXML () {Try {            //Read XMLSaxreader reader =NewSaxreader (); Document Doc= Reader.read ("Xml/students.xml"); //Get root nodeElement root =doc.getrootelement (); //Get child node collectionList<element> stullist =root.elements (); //Traverse             for(Element ele:stullist) {//Get PropertiesString id = ele.attributevalue ("id"); System.out.println ("Student ID:" +ID); //gets the text content of the child node nameString name = Ele.elementtext ("name"); //AgeString age = Ele.elementtext (' Age '); //SexString sex = Ele.elementtexttrim ("Sex"); //PhoneString phone = Ele.elementtexttrim ("Phone"); //AddressString address = Ele.elementtexttrim ("Address"); System.out.println ("Name:" + name + "\ t Age:" + ages + "\ t gender:" + sex + "\t\t phone:" + phone + "\t\t Address:" +address); }        } Catch(documentexception e) {e.printstacktrace (); }    }

Third, increase the node
//Add a new node     Public Static voidAddxml () {Try {            //read XML Creation ParserSaxreader reader=NewSaxreader (); //Create Document ObjectDocument doc=reader.read ("Xml/students.xml"); //Get root nodeElement root=doc.getrootelement (); //Create a new nodeElement student=root.addelement ("Student"); //Add PropertyStudent.addattribute ("id", "10020"); //Create child nodesStudent.addelement ("name"). SetText ("Zhang San Feng"); Student.addelement ("Age"). SetText ("108"); Student.addelement ("Sex"). SetText ("male")); Student.addelement ("Phone"). SetText ("13800138001")); Student.addelement ("Address"). SetText ("Wudangshan")); //Write XML//set character encoding and formattingOutputFormat format=NewOutputFormat (); Format.setencoding ("Utf-8"); //Create an output streamXMLWriter writer=NewXMLWriter (NewFileWriter ("Xml/students.xml"), format); //Write DocumentWriter.write (DOC); //Close the streamWriter.close (); //give a hintSystem.out.println ("====== Added success ======="); } Catch(documentexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }            }

Four, modify the node
//Modify node Contents According to id10013 will Harry's name = Wang Xiao, age 30, Gender: Male, Tel: 138000138000, Address: Beijing     Public Static voidModify () {Try {            //creating the Saxreader parserSaxreader reader=NewSaxreader (); //Create documentDocument doc=reader.read ("Xml/students.xml"); //root node foundElement root=doc.getrootelement (); //Child node CollectionList<element> studentlist=root.elements (); //Traverse Lookup             for(Element ele:studentlist) {if(Ele.attributevalue ("id"). Equals ("10013")) {ele.element ("Name"). SetText ("Wang Xiao Wu")); Ele.element ("Age"). SetText ("30"); Ele.element ("Sex"). SetText ("male")); Ele.element ("Phone"). SetText ("138000138000")); Ele.element ("Address"). SetText ("Beijing")); }            }                //Write XML//set character formatting and encodingOutputFormat format=NewOutputFormat (); Format.setencoding ("Utf-8"); XMLWriter writer=NewXMLWriter (NewFileWriter ("Xml/students.xml"), format); //Write document toWriter.write (DOC); //Close the streamWriter.close (); //give a hintSystem.out.println ("= = = Modified = = = = ="); } Catch(documentexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }

V. Deleting a node XML
/removing nodes from Wang Xiao Delete node Public Static voidDelete () {Try {            //creating the Saxreader parserSaxreader reader=NewSaxreader (); //Create Document ObjectDocument doc=reader.read ("Xml/students.xml"); //Get root nodeElement root=doc.getrootelement (); //CollectionList<element> stulist=root.elements (); //Traverse             for(Element ele:stulist) {if(Ele.attributevalue ("id"). Equals ("10013"))){                    //Gets the parent node and deletes the nodeele.getparent (). Remove (Ele); }            }            //Write XML//set character encoding formatOutputFormat format =NewOutputFormat (); Format.setencoding ("Utf-8"); //output StreamXMLWriter writer=NewXMLWriter (NewFileWriter ("Xml/students.xml"), format);            Writer.write (DOC);            Writer.close (); System.out.println ("= = = Delete succeeded = = ="); } Catch(documentexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }

Java Starts from scratch 43 (dom4j parsing 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.