Read and write xml using dom4j

1, examples

Java code
  1. public class XMLUtils (
  2. / **
  3. * Generated xml file
  4. * @ Param doc
  5. * @ Param fileName
  6. * @ Param encoding
  7. * /
  8. public static void createXMLFile (Document doc, String fileName, String encoding) (
  9. XMLWriter writer = null;
  10. try (
  11. if (StringUtils.isNotEmpty (encoding)) (
  12. OutputFormat format = OutputFormat.createPrettyPrint ();
  13. format.setEncoding (encoding); / / specify the XML encoding
  14. writer = new XMLWriter (new FileWriter (fileName), format);
  15. ) Else (
  16. writer = new XMLWriter (new FileWriter (fileName));
  17. )
  18. writer.write (doc);
  19. ) Catch (IOException e) (
  20. e.printStackTrace ();
  21. ) Finally (
  22. try (
  23. writer.close ();
  24. ) Catch (IOException e) (
  25. e.printStackTrace ();
  26. )
  27. )
  28. )
  29. / **
  30. * Create Document and returns root node
  31. * @ Param root_label root tag
  32. * @ Return
  33. * /
  34. public static Document createDocument (String root_label) (
  35. Document doc = DocumentHelper.createDocument ();
  36. doc.setRootElement (doc.addElement (root_label));
  37. return doc;
  38. )
  39. / **
  40. * A string into XML
  41. * @ Param xml_string
  42. * @ Return
  43. * /
  44. public static Document createDocumentFromXmlString (String xml_string) (
  45. if (StringUtils.isEmpty (xml_string)) (
  46. xml_string = "<students> <class> test </ class> </ students>";
  47. )
  48. Document document = null;
  49. try (
  50. document = DocumentHelper.parseText (xml_string);
  51. ) Catch (DocumentException e) (
  52. e.printStackTrace ();
  53. )
  54. return document;
  55. )
  56. / **
  57. * To add sub-nodes node
  58. * @ Param root the relative root
  59. * @ Param newNode the new node
  60. * @ Param nodeId node Id
  61. * @ Param elements node element
  62. * /
  63. public static void addNodeElement (Element root, String newNode, String nodeId, Map elements) (
  64. Element _newNode = root.addElement (newNode);
  65. _newNode.addAttribute ("id", nodeId). addAttribute ("no", nodeId); / / Set properties
  66. Iterator it = elements.entrySet (). Iterator ();
  67. while (it.hasNext ()){// node elements and values under the
  68. Map.Entry entry = (Map.Entry) it.next ();
  69. Object key = entry.getKey ();
  70. Object value = entry.getValue ();
  71. _newNode.addElement ((String) key). setText ((String) value);
  72. )
  73. )
  74. / **
  75. * XML document or node into a string
  76. * @ Param filePath
  77. * @ Return
  78. * /
  79. public static String readXMLAsString (String filePath) (
  80. SAXReader reader = new SAXReader ();
  81. Document document = null;
  82. try (
  83. document = reader.read (new File (filePath));
  84. / / Element root = document.getRootElement ();
  85. ) Catch (DocumentException e) (
  86. e.printStackTrace ();
  87. )
  88. return document.asXML ();
  89. )
  90. / **
  91. * Print all the child nodes node
  92. * @ Param element
  93. * /
  94. publicstatic void printAllChildNode (Element element) (
  95. / / Loop current node attributes
  96. Iterator attrs = element.attributeIterator ();
  97. while (attrs.hasNext ()) (
  98. Attribute attr = (Attribute) attrs.next ();
  99. System.out.println (attr.getName () + "=" + attr.getText ());
  100. )
  101. / / Loop the child element nodes
  102. Iterator elements = element.elementIterator ();
  103. while (elements.hasNext ()) (
  104. Element ele = (Element) elements.next ();
  105. if (ele.attribute ("id") == null) (
  106. System.out.println (ele.getName () + "=" + ele.getText ());
  107. )
  108. / / Recursive call
  109. printAllChildNode (ele);
  110. )
  111. )
  112. / ***
  113. * To read data xpath
  114. * @ Param filePath
  115. * @ Param xpath
  116. * /
  117. public static void printElementsByXPath (String filePath, String xpath) (
  118. SAXReader reader = new SAXReader ();
  119. try (
  120. Document doc = reader.read (new File (filePath));
  121. List properties = doc.selectNodes (xpath);
  122. Iterator it = properties.iterator ();
  123. while (it.hasNext ()) (
  124. Element elm = (Element) it.next ();
  125. System.out.println (elm.getText ());
  126. )
  127. )
  128. catch (Exception ex) (
  129. ex.printStackTrace ();
  130. )
  131. )
  132. public static void main (String [] args) (
  133. Map <String,String> elements = new HashMap <String,String> ();
  134. elements.put ("name", "Joe Smith");
  135. elements.put ("sex", "M");
  136. elements.put ("age", "20");
  137. Document doc = XMLUtils.createDocumentFromXmlString ("<students> </ students>");
  138. doc.getRootElement (). addAttribute ("year", "2000");
  139. XMLUtils.addNodeElement (doc.getRootElement (), "student", "20090313001", elements);
  140. elements.clear ();
  141. elements.put ("name", "John Doe");
  142. elements.put ("sex", "M");
  143. elements.put ("age", "21");
  144. XMLUtils.addNodeElement (doc.getRootElement (), "student", "20090313002", elements);
  145. String filePath = "D: / test.xml";
  146. XMLUtils.createXMLFile (doc, filePath, "GBK");
  147. / / System.out.println (XMLUtils.readXMLAsString (filePath));
  148. XMLUtils.printElementsByXPath (filePath, "/ students / student [@ id = \" 20090313001 \ "] / name");
  149. XMLUtils.printAllChildNode (doc.getRootElement ());
  150. )
  151. )

public class XMLUtils {
        /**
         *  Generates an XML file  
         * @param doc
         * @param fileName
         * @param encoding
         */
        public static void createXMLFile(Document doc,String fileName,String encoding){
                XMLWriter writer = null;
                try{
                        if(StringUtils.isNotEmpty(encoding)){
                                OutputFormat format = OutputFormat.createPrettyPrint();
                    format.setEncoding(encoding);    //  The specified XML encoding          
                    writer = new XMLWriter(new FileWriter(fileName),format);
                        }else{
                                writer = new XMLWriter(new FileWriter(fileName));
                        }
                        writer.write(doc);
                }catch(IOException e){
                        e.printStackTrace();
                }finally{
                        try{
                                writer.close();
                        }catch(IOException e){
                                e.printStackTrace();
                        }
                }
        }
        
        /**
         *  Create a Document and returns the root node  
         * @param root_label     The root tag     
         * @return
         */
        public static Document createDocument(String root_label){
                Document doc = DocumentHelper.createDocument();
                doc.setRootElement(doc.addElement(root_label));
                return doc;
        }
        
        /**
         *  Converts a string into  XML
         * @param xml_string
         * @return
         */
        public static Document createDocumentFromXmlString(String xml_string){
                if(StringUtils.isEmpty(xml_string)){
                        xml_string = "<students> <class>test</class> </students>";
                }
                Document document = null;
                try {
                        document = DocumentHelper.parseText(xml_string);
                } catch (DocumentException e) {
                        e.printStackTrace();
                }
                return  document;
        }
        
        /**
         *  To add the child nodes of node  
         * @param root        Relative root  
         * @param newNode     The new nexus  
         * @param nodeId      Nexus  Id
         * @param elements    Node elements  
         */
        public static void addNodeElement(Element root,String newNode,String nodeId,Map elements){
                Element _newNode = root.addElement(newNode);
                _newNode.addAttribute("id", nodeId).addAttribute("no", nodeId);// Setting properties  
                
                Iterator   it   =   elements.entrySet().iterator();     
                while(it.hasNext()){// Nexus of elements and values  
                          Map.Entry  entry = (Map.Entry)it.next();     
                          Object key = entry.getKey();     
                          Object value = entry.getValue();
                          _newNode.addElement((String)key).setText((String)value);
                }
        }
        
        /**
         *  Add a document or an XML node into a string  
         * @param filePath
         * @return
         */
        public static String readXMLAsString(String filePath){
                 SAXReader reader = new SAXReader();
         Document document=null;
                try {
                        document = reader.read(new File(filePath));
            //Element root=document.getRootElement();                
                } catch (DocumentException e) {
                        e.printStackTrace();
                }        
                        return document.asXML();
        }

        /**
         *  Print all the child nodes of the node  
         * @param element
         */
        public static void printAllChildNode(Element element){
                // Loop current node properties  
                Iterator attrs = element.attributeIterator();
                while(attrs.hasNext()){
                        Attribute attr = (Attribute)attrs.next();
                        System.out.println(attr.getName() + "=" + attr.getText());
                }
                
                // Loop the child element node  
                Iterator elements = element.elementIterator();
                while(elements.hasNext()){
                        Element ele = (Element)elements.next();
                        if(ele.attribute("id") == null){
                                System.out.println(ele.getName() + "=" + ele.getText());
                        }
                        
                        // Recursive calls  
                        printAllChildNode(ele);
                }
        }
        
        /***
         *  In XPath read data  
         * @param filePath
         * @param xpath
         */
        public static void printElementsByXPath(String filePath,String xpath){
            SAXReader reader = new SAXReader();
            
            try{
              Document  doc = reader.read(new File(filePath));
              
              List properties=doc.selectNodes(xpath);
              
              Iterator it=properties.iterator();
              
              while(it.hasNext()){
                Element elm=(Element)it.next();       
                System.out.println(elm.getText());
              }
              
            }
            catch(Exception ex){
               ex.printStackTrace();
            }
        }
        
        public static void main(String[] args){
                Map<String,String> elements = new HashMap<String,String>();
                elements.put("name", " Smith, John  ");
                elements.put("sex", " Male  ");
                elements.put("age", "20");
                Document doc = XMLUtils.createDocumentFromXmlString("<students></students>");
                doc.getRootElement().addAttribute("year", "2000");
                
                XMLUtils.addNodeElement(doc.getRootElement(), "student", "20090313001", elements);
                
                elements.clear();
                elements.put("name", " Paul Lee  ");
                elements.put("sex", " Male  ");
                elements.put("age", "21");
                XMLUtils.addNodeElement(doc.getRootElement(), "student", "20090313002", elements);
                
                String filePath = "D:/test.xml";
                XMLUtils.createXMLFile(doc, filePath, "GBK");
                
                //System.out.println(XMLUtils.readXMLAsString(filePath));
                
                XMLUtils.printElementsByXPath(filePath, "/students/student[@id=\"20090313001\"]/name");
                XMLUtils.printAllChildNode(doc.getRootElement());
          }
}


Second, the use XPATH

Xml Code
  1. <AAA>
  2. <BBB/>
  3. <CCC/>
  4. <BBB/>
  5. <BBB/>
  6. <DDD>
  7. <BBB/>
  8. </ DDD>
  9. <CCC/>
  10. </ AAA>

<AAA> 
          <BBB/> 
          <CCC/> 
          <BBB/> 
          <BBB/> 
          <DDD> 
               <BBB/> 
          </DDD> 
          <CCC/> 
</AAA> 


(1) If it is a slash "/" start, which is described in the request element's absolute path.
Example structure:

  • Access element "AAA "----" / AAA ".
  • Access element "CCC" --- "/ AAA / CCC", visit the following sub-root node AAA CCC, the regular collection by the two nodes.
  • Visit the root node AAA DDD sub-sub-node BBB: "/ AAA / DDD / BBB".


(2) If the path expression to "/ /" start, it will find all the elements of compliance rules <br /> example structure:

  • "/ / BBB", select all the elements of <BBB/>, in this case a total of four
  • "/ / DDD / BBB", select the element node "DDD" child node under the "BBB", only to meet the elements of "BBB" to "DDD" sub-element will be selected, in this case 1.


(3) "*" in front of the path chosen by the positioning of all elements of <br /> Example:

  • "/ AAA / *" said the root of all the elements of choice
  • "/ * / CCC" Select a parent element of the "CCC" element ,"/*/*/ BBB "select the third class under the root of all the" BBB "element
  • "//*" That match all of the elements


(4) the expression in square brackets can be further specified element number in square brackets, said the location of the selected elements of the collection, last () function that sets the selected element the last element

  • "/ AAA / BBB [2]" said Root "BBB" A collection of elements of the second element
  • "/ AAA / BBB [last ()]" said Root "BBB" the last element of the collection element


(5) "@" means property

Xml Code
  1. <AAA>
  2. <BBB Id = "b1" />
  3. <BBB Id = "b2" />
  4. <BBB Name = "bbb" />
  5. <BBB/>
  6. </ AAA>

<AAA> 
          <BBB id = "b1"/> 
          <BBB id = "b2"/> 
          <BBB name = "bbb"/> 
          <BBB/> 
</AAA> 


  • "/ / @ Id" mean that all named "id" attribute
  • "/ / BBB [@ id]" that all elements with ID attributes of the BBB
  • "/ / BBB [@*]" said the BBB with all elements of property, in this case <BBB/> will not be selected, the other three were selected
  • "/ / BBB [not (@*)]" that the element has no attributes, in this case <BBB/> is selected, the other three elements are not selected


(6) The value of the property can be used as selection criteria, the function "normalize-space" can be removed to the head and tail of the space, or replaced with a single space

Xml Code
  1. <AAA>
  2. <BBB Id = "b1" />
  3. <BBB Name = "bbb" />
  4. <BBB Name = "bbb" />
  5. </ AAA>

<AAA> 
          <BBB id = "b1"/> 
          <BBB name = " bbb "/> 
          <BBB name = "bbb"/> 
</AAA> 


  • "/ / BBB [@ id = 'b1']": select the attribute value "b1" elements "BBB"
  • "/ / BBB [@ name = 'bbb']": select the attribute value of "bbb" of the elements, attention to a property called name as each element of "BBB", its value has spaces, will not be selected.
  • "/ / BBB [normalize-space (@ name) = 'bbb']": select the name "name", and its value "bbb", the value can have spaces before and after, this example will select two "BBB "Elements


(7) function count (*): calculate the number of selected elements

  • "//*[ Count (BBB) = 2] ", selected with the two" BBB "sub-elements of elements
  • "//*[ Count (*) = 2] ", select the element contains two child elements
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Read and write xml using dom4j

  • Build flex + spring + blazeds + hibernate application

    Build flex + spring + blazeds + hibernate application First, set up the project blazeds 1, will blazeds.war extract to a directory, such as: myflex /; 2, set up java works were such as: MyFlex, in the orientation of selection create project from exis ...

  • JAVA EE JSP_JNDI

    dsfdsa http://lindows.javaeye.com/admin/blogs/213348 Tomcat 6 with the connection pool data source configuration http://www.blogjava.net/ec2008/archive/2008/07/19/216063.html project: test Driver path: D: \ workspace \ test \ WebRoot \ WEB-INF \ lib ...

  • Hibernate connection pool configuration

    Hibernate connection pool configuration <! - Jdbc -> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </ property> <property name="connection.url"> jdbc: oracle: thin: @ 10.203.14.132:15

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • First Hibernate Example

    Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and other co

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

  • Hibernate secondary cache

    Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...

  • The level Hibernate cache

    Hibernate cache level: (1) a cache is very short and the session life cycle consistent, also known as session-level cache-level cache or transaction-level cache (2) Ways of Supporting level cache: get (); load (); iterator (); only entity object cach ...

  • Hibernate's lazy strategy

    hibernate Lazy strategy can be used in: <class> tag, it can be true / false Tags can <PROPERTY> values true / false type of necessary tools to enhance <set> <list> can tag values true / false / extra <many-to-one> <on ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries