DOM4J (Java code)

Source: Internet
Author: User
Tags flush gettext join joins

Import Java.io.File;


import Java.io.FileWriter;


import Java.util.Iterator;


import java.util.List;


import Org.dom4j.attribute;import org.dom4j.Document;


import Org.dom4j.DocumentHelper;


import org.dom4j.Element;


import Org.dom4j.io.outputformat;import Org.dom4j.io.SAXReader;


import Org.dom4j.io.XMLWriter;


public class Dom4jdemo {


  


public boolean createxml (String fileName) {


Boolean isok= false;


//Establish Document Object


Document doc= documenthelper.createdocument ();


//create XML document root books


Element students= doc.addelement ("students");


students.addcomment ("This are a test for dom4j");//Join one line of comments


/** joins the first student node * * *


Element student= students.addelement ("student");/join the First Student node


Student.addattribute ("value", "God");//Add Value property and Values


Element name= student.addelement ("name");//Join name node


name.settext ("Finina");//Set value for name


Element age=student.addelement ("age");//Join the Age node


Age.settext ("25");//Set value for age


Element sex=student.addelement ("sex");/join Sex node


sex.settext ("male");//Set value for sex


/** joins the second student node * * *


student= students.addelement ("student");


Student.addattribute ("value", "cat");


name= student.addelement ("name");


Name.settext ("Fly");


age=student.addelement ("Age");


Age.settext ("17");


sex=student.addelement ("sex");


Sex.settext ("female");


/** Join the Team node * *


Element team=students.addelement ("team");


team.addtext ("05093A");


   /**


* Writes the contents of doc to the XML file


     **/


try{


OutputFormat format= Outputformat.createprettyprint ()//Formatting


format.setencoding ("GBK"), if necessary, cannot parse Chinese


//Output as file


XMLWriter writer= New XMLWriter (New FileWriter (fileName), format);


Writer.write (DOC);


Writer.flush ();


     //


isok= true;


}catch (Exception e) {


E.printstacktrace ();


    }


return isOk;


  }


public boolean modifigxml (String oldfilename,string newfilename) {


Boolean isok= false;


try{


saxreader reader= New Saxreader ()//create SAX Reader


document doc= Reader.read (new file (Oldfilename))//Read all file contents to live Document Object


/**: If the content of the Value property in the student node is God, modify it to King


* Because you can't be too arrogant


       */


List list= doc.selectnodes ("/students/student/@value")//Search out all students nodes under the student node in the location of the value attribute into the collection


iterator iter= List.iterator ()//load iterator


//Iteration Set


while (Iter.hasnext ()) {


attribute attr= (attribute) Iter.next ();


if (Attr.getvalue (). Equals ("God"))//ratio is equal to the value


Attr.setvalue ("King");/Set Value


      }


list= doc.selectnodes ("/students/team")//Search out all the team node locations under the students node into the collection


iter= List.iterator ()//load iterator


//Iteration Set


if (Iter.hasnext ()) {


element team= (Element) Iter.next ();


team.settext ("05084A");/Set Value


Element teacher= team.addelement ("Teacher");//Add Node


Teacher.settext ("Godfather");//Set value for the new node


Teacher.addattribute ("Skill", "programme");//Add attributes to the new node


      }


/** Modify the third: if the age content is 17, delete the node


* Minors need to be protected ...


      */


list= doc.selectnodes ("/students/student")//Search out all students node locations under student nodes into the collection


iter= List.iterator ()//load iterator


//Iteration Set


while (Iter.hasnext ()) {


element elem= (Element) Iter.next ();


iterator iterelem= elem.elementiterator ("age");//Generate an iterator for all the age nodes under the node


//Iteration Set


if (Iterelem.hasnext ()) {


element remtitle= (Element) Iterelem.next ();


if (Remtitle.gettext (). Equals ("17"))//Contrast value


Elem.remove (remtitle)//Remove the node


        }


      }


Write the contents of doc to the file


OutputFormat format= Outputformat.createprettyprint ()//Formatting


format.setencoding ("GBK"), if necessary, cannot parse Chinese


//Output as file, the above operation is only modified in memory, need to save as a file to confirm the modification


XMLWriter writer= New XMLWriter (New FileWriter (newfilename), format);


Writer.write (DOC);


Writer.flush ();


isok= true;


}catch (Exception e) {


E.printstacktrace ();


    }


return isOk;


  }


 /**


*the Method ReadXML


  */


public void ReadXML (String fileName) {


try{


file file= (filename);//Create a Document object


saxreader reader= New Saxreader ()//create SAX Reader


document doc= reader.read (file)//read content generate Document object


Element root= doc.getrootelement ();//Get root node


search (root);//start traversing


}catch (Exception e) {


E.printstacktrace ();


    }


  }


  


//Recursive traversal


private void Search (Element root) {


iterator it_element= Root.elementiterator ()//To organize the elements contained under the root node into an iterator


//Iterative


while (It_element.hasnext ()) {


element element= (Element) It_element.next ();


if (!element.gettext (). Equals (""))


      {

The value of the
System.out.println (element.getname () + "node is" +element.gettext ());


      }


Else


      {


System.out.println (Element.getname () + "node");


      }


iterator it_attr= element.attributeiterator ();


while (It_attr.hasnext ()) {


attribute attr= (attribute) It_attr.next ();


if (attr!=null)


        {

The value of the
System.out.println (element.getname () + "node" +attr.getname () + "is" + attr.getvalue ());


        }


      }


search (element);//Recursive call


    }


  }


 /**


*the Method Main


  */


public static void Main (string[] args) {


long start= system.currenttimemillis ();/Start Timing


Dom4jdemo dom4jdemo= New Dom4jdemo ();


String filename= "Dom4jdemo.xml";


String newfilename= "New_dom4jdemo.xml";


System.out.println (filename+ "in the process of creating ...");


boolean isok_create= dom4jdemo.createxml (fileName);


if (isok_create) System.out.println (filename+ "Create success!");


Else System.out.println ("Create failed! Please try again after checking!");


    


System.out.println ("in update ...");


boolean isok_modi= dom4jdemo.modifigxml (FileName, NewFileName);


if (isok_modi) System.out.println ("Congratulations, update complete!");


   //


System.out.println ("Reading Files" +filename+ "...");


System.out.println ("------------------------------------------------");


Dom4jdemo.readxml (fileName);


System.out.println ("------------------------------------------------");


System.out.println (filename+ "read success!");


System.out.println ("Reading Files" +newfilename+ "...");


System.out.println ("------------------------------------------------");


Dom4jdemo.readxml (NewFileName);


System.out.println ("------------------------------------------------");


SYSTEM.OUT.PRINTLN (filename+ "read success!");


System.out.println ("Time Consuming:" + (System.currenttimemillis ()-start) + "milliseconds!");


  }


}

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.