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
分类:Java 时间:2010-06-16 人气:209
分享到:
blog comments powered by Disqus

相关文章

  • JAVA code automatically discuz 7.2 post on the forum 2011-01-06

    Met a Powered by discuz 7.2! The Forum, integral constraints, very unhappy, and posted to increase the points, so I spent some time pondering getting a automatic posting machine, the following is the basic principle of the code and instructions to au

  • Java实现Map集合二级联动示例 2015-03-17

    Java实现Map集合二级联动示例,需要的朋友可以参考下 Map集合可以保存键值映射关系,这非常适合本实例所需要的数据结构,所有省份信息可以保存为Map集合的键,而每个键可以保存对应的城市信息,本实例就是利用Map集合实现了省市级联选择框,当选择省份信息时,将改变城市下拉选择框对应的内容. 思路分析: 1. 创建全国(省,直辖市,自治区)映射集合,即LinkedHashMap对象,使用Map接口的put()方法向集合中添加指定的省与城市的映射关系,其中值为String型一维数组. 代码如下: C

  • java遍历map方法 2014-03-14

    import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class MapTest { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("1", "1"); map.put(

  • Link to help java code code-sharing 2011-04-28

    package com.asflex.utils; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class ShareLink { public static final String KAIXIN = "kaixin";

  • With the JAVA code to access a URL address is available how to write? 2010-10-26

    With the JAVA code to access a URL address is available how to write? First of all, tell us about get by: String mainDomain = agentFacade.getVirtualHostService().getMainDomainName(domain); String webServer =this.getVzzjzManageService().getVZZJZWebSit

  • java集合map取key使用示例 java遍历map 2013-11-04

    这篇文章主要介绍了java集合map取key使用示例,需要的朋友可以参考下 for (Iterator i = keys.iterator(); i.hasNext() { String key = (String) i.next(); String value = (String) map.get(key); text+=key + " = " + value; } 复制代码 代码如下: <span style="border-collapse: collapse;

  • public static void main (String args []) parameters 2010-05-15

    String args [] is the main function of main parameters, namely array of strings. Using eclipse in the editing, right-click to run the Java files in the Run As option, select Run Configurations. Main class in the Project and complete the project, resp

  • 为什么 main 方法是 public static void? 2014-01-16

    0.引言: 之前在校招时,旁边的面试官问过这样一个问题:如何不在 main 函数里打印出一行字符串呢(也不允许在main里调用函数)? 如果你不能回答上来没关系,看了本文你就会有了答案.其实 main 函数我们每天 coding 都会接触,但是不一定每个同学都了解或注意到它为什么要这么设计,为什么不能那么写? 言归正传,Main方法是我们学习Java编程语言时知道的第一个方法,你是否曾经想过为什么 main 方法是 public.static.void 的?当然,很多人首先学的是C和C++,但是

  • java code programming optimization 2010-03-26

    Procedures for the use of available resources (memory, CPU time, network bandwidth, etc.) is limited, the purpose of optimization is to allow programs to use the least resources to complete the scheduled tasks. Optimization usually contains two aspec

  • java code for the page 2010-02-09

    Recent studies have crawled pages, and discovered to obtain the page's encoding format, Java implementations is not ready, although there are a csdn Daren wrote an article, with code, unfortunately, I did not find the relevant package, a last resort,

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.647 (s). 12 q(s)