Dom4j reads XML

Source: Internet
Author: User
Tags xml cdata

Dom4j is a Java xml api, similar to JDOM, used to read and write XML files. Dom4j is a very good Java xml api with excellent performance, powerful functionality, and extreme ease of use. It is also an open source software, 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.

 

As mentioned above, dom4j is so good and easy to use. We will share with you some usage of dom4j from today on.

 

 

The main interfaces of dom4j are defined in the org. dom4j package:
Attribute Attribute defines XML attributes.
Branch Branch defines a common behavior for nodes that can contain sub-nodes, such as XML elements and documents,
CDATA CDATA defines the xml cdata Region
Characterdata Characterdata is an excuse to identify character-based nodes. Such as CDATA, comment, text.
Comment Comment defines the XML annotation Behavior
Document Defines XML documents
Documenttype Documenttype defines XML doctype Declaration
Element Element defines XML elements
Elementhandler Elementhandler defines the processor of the Element Object
Elementpath Used by elementhandler to obtain the path level information currently being processed
Entity Entity defines XML Entity
Node Node defines polymorphism for all XML nodes in dom4j.
Nodefilter Nodefilter defines the behavior of a filter or predicate generated in the dom4j node (predicate)
Processinginstruction Processinginstruction defines XML processing instructions.
Text Text defines XML text nodes.
Visitor Visitor is used to implement the visitor mode.
Xpath After analyzing a string, XPath provides an XPATH expression.

 

 

 

 

To understand this interface, you must understand the inheritance relationship of the interface:
  • Interface java. Lang.Cloneable
    • Interface org. dom4j.Node
      • Interface org. dom4j.Attribute
      • Interface org. dom4j.Branch
        • Interface org. dom4j.Document
        • Interface org. dom4j.Element
      • Interface org. dom4j.Characterdata
        • Interface org. dom4j.CDATA
        • Interface org. dom4j.Comment
        • Interface org. dom4j.Text
      • Interface org. dom4j.Documenttype
      • Interface org. dom4j.Entity
      • Interface org. dom4j.Processinginstruction

 

 

Reading and Writing XML documents mainly depends on the org. dom4j. Io package, which provides two different methods: domreader and saxreader, and the call method is the same. This is the benefit of relying on interfaces.

 

[Java]View Plain Copy
  1. // Read XML from the file, input the file name, and return the XML file
  2. Public document read (string filename) throws malformedurlexception, using entexception {
  3. Saxreader reader = new saxreader ();
  4. Document document = reader. Read (new file (filename ));
  5. Return document;
  6. }

Reader's read method is overloaded and can be read through different parameters such as inputstream, file, and URL. The resulting document object contains the entire XML table.
According to my own experience, the character encoding read is converted according to the encoding defined in the XML file header. In case of garbled characters, make sure that the names of all codes are consistent.

 

 

In the following example, the saxreader class reads XML files through inputstream:

 

XML file to be read:

 

[HTML]View Plain Copy
  1. <? XML version = "1.0" encoding = "UTF-8"?>
  2. <Config>
  3. <DB-Info>
  4. <Driver-Name> oracle. JDBC. Driver. oracledriver </driver-Name>
  5. <URL> JDBC: oracle: thin: @ localhost: 1522: mydb </URL>
  6. <User-Name> DRP </user-Name>
  7. <Password> DRP </password>
  8. </DB-Info>
  9. </Config>


Class for reading XML files:

 

[Java]View Plain Copy
  1. Package com. util;
  2. Import java. Io. inputstream;
  3. Import java. util. hashmap;
  4. Import java. util. List;
  5. Import java. util. Map;
  6. Import org. dom4j. Document;
  7. Import org. dom4j. extends entexception;
  8. Import org. dom4j. element;
  9. Import org. dom4j. Io. saxreader;
  10. /**
  11. * Parse sys-config.xml files
  12. * @ Author Ronaldinho
  13. *
  14. */
  15. Public class xmlconfigreader {
  16. // Lazy
  17. Private Static xmlconfigreader instance = NULL;
  18. // Save JDBC-related information
  19. Private jdbcconfig = new jdbcconfig ();
  20. Private xmlconfigreader (){
  21. // Create a saxreader object
  22. Saxreader reader = new saxreader ();
  23. // Obtain the relative path of the file through the class loader of the current thread and read the buffered input stream
  24. Inputstream in = thread. currentthread (). getcontextclassloader (). getresourceasstream ("sys-config.xml ");
  25. Try {
  26. // Read XML files through streams
  27. Document Doc = reader. Read (in );
  28. // Read JDBC-related information
  29. Element drivernameelt = (element) Doc. SelectObject ("/config/DB-info/driver-name ");
  30. Element urlelt = (element) Doc. SelectObject ("/config/DB-info/url ");
  31. Element usernameelt = (element) Doc. SelectObject ("/config/DB-info/user-name ");
  32. Element passwordelt = (element) Doc. SelectObject ("/config/DB-info/password ");
  33. // Set JDBC Information
  34. Jdbcconfig. setdrivername (drivernameelt. getstringvalue ());
  35. Jdbcconfig. seturl (urlelt. getstringvalue ());
  36. Jdbcconfig. setusername (usernameelt. getstringvalue ());
  37. Jdbcconfig. setpassword (passwordelt. getstringvalue ());
  38. } Catch (incluentexception e ){
  39. E. printstacktrace ();
  40. }
  41. }
  42. Public static synchronized xmlconfigreader getinstance (){
  43. If (instance = NULL ){
  44. Instance = new xmlconfigreader ();
  45. }
  46. Return instance;
  47. }
  48. }

 

The above method generates an object in singleton mode. This object instantiates a saxreader and then loads the XML file into the stream. Then, use the read () method of saxreader to convert it into a document object. Then, the document object is used to get the node value of the XML file.

 

Today, we will briefly introduce how to use dom4j to read XML files. We will talk about other usage later. Don't worry.

 

PS: Thank you for your criticism!

Dom4j reads 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.