XML programming-DOM4J

Source: Internet
Author: User
Tags ibm developerworks
Dom4j is a Java XMLAPI, similar to jdom, used to read and write XML files. Dom4j is a very good JavaXMLAPI with excellent performance, powerful functionality, and extremely easy to use features. it is also an open source software that can be found on SourceForge. You can also find an article on IBMdeveloperWorks to evaluate the performance, functions, and usability of mainstream javaxmlapis. Therefore, you can know that dom4j is excellent in any aspect. Now we can see that more and more Java software are using dom4j to read and write XML, special value XML programming-DOM4J

Overview


Dom4j is a Java xml api, similar to jdom, used to read and write XML files. Dom4j is a very good JavaXML API with excellent performance, powerful functionality, and extremely easy to use features. it is also an open source software that can be found on SourceForge. You can also find an article on IBM developerWorks to evaluate the performance, functionality, and usability of mainstream Java XML APIs. Therefore, you can know that dom4j is excellent in any aspect. Now we can see that more and more Java software are using dom4j to read and write XML. it is particularly worth mentioning that Sun's JAXM is also using dom4j. This is a required jar package. Hibernate also uses it to read and write configuration files.

PS: one of the reasons why DOM4J is so powerful is that it supports the XPath technology. DOM4J also has relevant reference documents. you can search and download the documents you need.

Why DOM4J?

Previously, the two technologies described in the blog are DOM and SAX. the disadvantage of the former is that it consumes memory, while the latter is that it can only perform read operations, while DOM4J can both submit efficiency, you can also perform crud operations.

PS: To use DOM4J, you need to import the corresponding basic JAR package. if you use the DOM4J extension function, you also need to import the extension JAR package.

DOM4J three methods to get the Document object using entry DOM4J 1. read the XML file and get the document object (commonly used)
    SAXReader reader = new SAXReader();    Document   document = reader.read(new File(“src/input.xml"));
2. parse the XML text to obtain the document object.
    String text = "
 ";    Document document = DocumentHelper.parseText(text);
3. create a document object
Document document = incluenthelper. createDocument (); // create the root node Element root = document. addElement ("members ");

PS: import the corresponding JAR package.



Node object 1. get the root node of the document
    Element root = document.getRootElement();



2. obtain the subnode of a node



Element element = node. element ("name ");
3. get node content
String text1 = node. getText (); String text2 = node. getTextTrim (); // remove spaces before and after the content
4. retrieve all the child nodes named "member" under a node and traverse them.
    List nodes = rootElm.elements("member");    for (Iterator it = nodes.iterator(); it.hasNext();) {          Element elm = (Element) it.next();          // do something    }
5. traverse all subnodes under a node
    for(Iterator it=root.elementIterator();it.hasNext();){        Element element = (Element) it.next();           // do something      }
6. add a subnode under a node
    Element ageElm = newMemberElm.addElement("age");
7. set node text
    element.setText("29");
8. delete a node
// ChildElm is the node to be deleted, and parentElm is the parent node parentElm. remove (childElm );
9. add a CDATA node
    Element contentElm = infoElm.addElement("content");    contentElm.addCDATA(diary.getContent());


PS: note that nodes cannot be accessed across layers.


Node object attribute 1. get an attribute under a node
Element root = document. getRootElement (); // Attribute name attribute = root. Attribute ("size ");
2. get the attribute text
     String text=attribute.getText();
3. delete an attribute
    Attribute attribute=root.attribute("size");    root.remove(attribute);
4. traverse all attributes of a node
     Element root=document.getRootElement();        for(Iterator it=root.attributeIterator();it.hasNext();){           Attribute attribute = (Attribute) it.next();           String text=attribute.getText();            System.out.println(text);     }
5. set attributes and text of a node
    newMemberElm.addAttribute("name", "sitinspring");
6. set the attribute text
    Attribute attribute=root.attribute("name");     attribute.setText("sitinspring");


Insert a node at a specified position

1. get the list of inserted nodes (list)

2. call list. add (index, elemnent). The index determines the insert position of the element.

The Element can be obtained through the incluenthelper object. Sample code:

Element aaa = incluenthelper. createElement ("aaa"); aaa. setText ("aaa"); List list = root. element ("book "). elements (); list. add (1, aaa); // update document


Write a document to an XML file


1. if the document is in full English


XMLWriter writer = new XMLWriter(new  FileWriter("output.xml"));writer.write(document);writer.close();
2. if the document contains Chinese characters
OutputFormat outputFormat = OutputFormat.createPrettyPrint();outputFormat.setEncoding("utf-8");XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/com/pc/XML8.xml"), outputFormat);xmlWriter.write(document);xmlWriter.close();

PS: garbled because the output character set cannot recognize Chinese characters, so you can set it to "UTF-8" through the setEncoding method of OutputFormat, and then use the XMLWriter parameter (OutputStream out, OutputFormat format) the constructor can solve the garbled text problem. as to why the createPrettyPrint method is used, the output format is more in line with people's reading habits.


Comprehensive cases

XML8.xml

 
 <班级 班次="1班" 编号="C1">
  <学生 学号="n1" 性别="男" 授课方式="面授" 朋友="n2" 班级编号="C1">
   <名字>
    
Zhang San
   
   <年龄>
    
20
   
   <介绍>
    
Good
   
  
  <学生 学号="n2" 性别="女" 授课方式="面授" 朋友="n1 n3" 班级编号="C1">
   <名字>
    
Li Si
   
   <年龄>
    
18
   
   <介绍>
    
Good
   
  
  <学生 学号="n3" 性别="男" 授课方式="面授" 朋友="n2" 班级编号="C1">
   <名字>
    
Wang Wu
   
   <年龄>
    
22
   
   <介绍>
    
Very good
   
  
  <学生 性别="男" 班级编号="C1">
   <名字>
    
James
   
   <年龄>
    
30
   
   <介绍>
    
Good
   
  
 


Package com. pc; import java. io. file; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. fileWriter; import java. io. IOException; import java. io. unsupportedEncodingException; import java. util. iterator; import java. util. list; import org. dom4j. document; import org. dom4j. extends entexception; import org. dom4j. export enthelper; import org. dom4j. element; import org. dom4j. io. outputFormat; import org. dom4j. io. SAXReader; import org. dom4j. io. XMLWriter; /***** @ author Switch * @ function use DOM4j to parse the XML file **/public class XML8 {// use DOM4j to perform the CRUD operation on XML public static void main (String [] args) throws Exception {// 1. get the parser SAXReader saxReader = new SAXReader (); // 2. specify the XML file to be parsed, Document document = saxReader. read (new File ("src/com/pc/XML8.xml"); // list (document. getRootElement (); // read (document); // readByXPath (document); // add (document); // delete (document); // updateElement (document ); // updateAttribute (document); // addByIndex (document, 3);} // update attributes (modify all class numbers to C2) public static void updateAttribute (Document document) throws Exception {// get the List of all students
 
  
Students = document. getRootElement (). elements ("student"); for (Element e: students) {// modify the class number e. addAttribute ("class no.", "C2");} updateToXML (document);} // update the element (add the age of all students to + 3) public static void updateElement (Document document) throws Exception {// get the List of all students
  
   
Students = document. getRootElement (). elements ("student"); for (Element e: students) {// Retrieve age Element age = e. element ("age"); age. setText (Integer. parseInt (age. getTextTrim () + 3 + "");} updateToXML (document);} // delete an element (delete the first student) public static void delete (Document document) throws Exception {// locate Element stu = document. getRootElement (). element ("student"); // delete stu. getParent (). remove (stu); // update updateToXML (document);} // add the element to the specified position public static void addByIndex (Document document, int index) throws Exception {// create an Element newStu = incluenthelper. createElement ("student"); newStu. setText ("Xiaohua"); // Obtain the listList of all students
   
    
Students = document. getRootElement (). elements ("student"); // add students by index. add (index, newStu); // update updateToXML (document);} // add elements (add a student to xml) public static void add (Document document) throws Exception {// create a student node object Element newStu = incluenthelper. createElement ("student"); // add the attribute newStu to the element. addAttribute ("student ID", "n4"); Element newStuName = incluenthelper. createElement ("name"); Element newStuAge = incluenthelper. createElement ("age"); Element newStuIntro = incluenthelper. createElement ("Introduction"); // mount the child element to newStu under the student node. add (newStuName); newStu. add (newStuAge); newStu. add (newStuIntro); // mount the student to the root node document. getRootElement (). add (newStu); // update updateToXML (document);} private static void updateToXML (Document document) throws UnsupportedEncodingException, FileNotFoundException, IOException {// update xml file // the output will contain Chinese garbled characters OutputFormat outputFormat = OutputFormat. createPrettyPrint (); outputFormat. setEncoding ("UTF-8"); XMLWriter xmlWriter = new XMLWriter (new FileOutputStream ("src/com/pc/XML8.xml"), outputFormat); xmlWriter. write (document); xmlWriter. close ();} // xpath technology, Cross-layer reading of an Element public static void readByXPath (Document document) throws Exception {// retrieve the first student Element student = (Element) document. selectSingleNode ("/class/student [1]"); System. out. println ("name:" + student. elementText ("name") + "\ t age:" + student. elementText ("age") + "\ t introduction:" + student. elementText ("Introduction") + "\ t gender:" + student. attributeValue ("gender");} // read a specified element (read the information of the first student) public static void read (Document document) throws Exception {// get the root Element root = document. getRootElement (); // root. elements ("student"); extracts all student elements under the root element // root. element ("student"); extract the first student Element under the root Element // extract the first student element under the root Element element student = (Element) root. elements ("student "). get (0); System. out. println ("name:" + student. elementText ("name") + "\ t age:" + student. elementText ("age") + "\ t introduction:" + student. elementText ("Introduction") + "\ t gender:" + student. attributeValue ("gender");} // traverses the xml file public static void list (Element element) {System. out. println ("element name:" + element. getName () + "\ telement content:" + element. getTextTrim (); Iterator
    
     
Iterator = element. elementIterator (); while (iterator. hasNext () {Element e = iterator. next (); // recursive list (e );}}}
    
   
  
 

The above is the content of DOM4J-XML programming. For more information, see The PHP Chinese website (www.php1.cn )!

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.