Teach you how to use Jdom to process XML documents quickly

Source: Internet
Author: User
Tags add filter object comparison string version versions access
Introduction of dom|xml| technique jdom and comparison with JAXB

Java + XML = JDOM!

This is the goal of Jdom designers. If you've ever used annoying sax or DOM to process XML, you'll know why you have Jdom or JAXB. At the JavaOne meeting, Jdom's main founder, Jason Hunter, had an excellent presentation on jdom technology, which was jdom makes XML easy.

In that document, Jdom was compared to the DOM, and I prefer to compare it to JAXB. Because JAXB and jdom are all developed to provide a more convenient XML processing interface in Java than Dom and sax, this problem is addressed in a completely different way. Jdom is handled like a tree operation with a DOM. JAXB uses DTD and binding patterns to generate Java code to access XML documents and to map XML to Java objects. You can decide which one to use according to the project's needs and personal preferences.

The comparison of Jdom with JAXB, in terms of its own characteristics:

1) Jdom is easier to get started than JAXB. Using JAXB, you would first write a DTD, and then you would write a binding pattern. Jdom has no such requirement, if you will be Java and XML, you can even say that you can use jdom just to see Jdom's Javadoc documentation.

2 after JAXB writes the DTD and the binding pattern, the XML document is mapped to the Java object, its data is the Java object's attribute, even the data type has been converted, therefore, accesses the XML document to be simpler than the jdom, can say is once and for all.

3 JAXB code generated by one DTD and binding mode can only access documents that are constrained by that DTD. If you want to access other XML documents, you need to rewrite the DTD and binding mode. Jdom can process any XML document, both constrained and unconstrained.

Currently there are no official versions of Jdom and JAXB. The latest version of Jdom is BETA8,JAXB is 1.0 early access, whose canonical version is 0.21. Comparatively speaking, jdom is more mature. For example, JAXB does not support namespaces and cannot write processing instructions to XML documents, and sometimes the line breaks and trailing spaces that we need to keep are automatically filtered out in JAXB, not even inside. Jdom There is no such restriction. If the above 3-point comparison is determined by the characteristics of Jdom and JAXB itself, it is almost impossible to change, and it shows that JAXB needs more work.

Get and install Jdom

The latest version of Jdom can be downloaded at http://jdom.org. Take the 2 jdom beta8 version as an example. After downloading, the Jdom jar file is the file Jdom.jar of the build directory and joins the CLASSPATH. In addition, Jdom also needs the support of those jar files such as Xerces.jar in the Lib directory. If you receive the following error in use:

       
        
         
        Java.lang.NoSuchMethodError
       
        


Or

       
        
         
        Java.lang.noclassdeffounderror:org/xml/sax/saxnotrecognizedexception
       
        


You need to ensure that Xerces.jar files in Classpath are located in other XML classes, such as JAXP or crimson, these class files, including previous versions of Xerces, may not support SAX2.0 or DOM level 2. This leads to the above error.

A simple example

Jdom is somewhat similar to DOM, but it is mainly implemented with sax, and you don't have to worry about handling speed and memory problems. In addition, there are almost no interfaces in the Jdom, the classes are all real classes, no class factory class. One of the most important packages in Org.jdom is the following classes:

       
        
         
        –attribute–cdata–comment–doctype–document–element–entityref–namespace–processinginstruction–text
       
        


Data entry uses an XML document to pass through the Org.jdom.input package, which in turn requires org.jdom.output. As mentioned above, it is possible to use the API documentation to see it.

Our example reads the XML file Examplea.xml, adds a processing instruction, modifies the price and author of the first book, adds an attribute, and then writes to the file Exampleb.xml:

       
        
Examplea.xml<?xml version= "1.0" encoding= "GBK"?><booklist><book> <name>java Programming Entry </ name> <author> John </author> <publishdate>2002-6-6</publishdate><price>35.0</ Application of price></book> <book><name>xml in Java </name><author> Dick </author>< publishdate>2002-9-16</publishdate><price>92.0</price></book></booklist>// Testjdom.javaimport org.jdom.*;import org.jdom.output.*;import org.jdom.input.*;import java.io.*;p ublic class Testjdom{public static void Main (String args[]) throws Exception{saxbuilder sb = new Saxbuilder ();//construct a document from a file. Because the encoding is already specified in the XML file, there is no need for document DOC = Sb.build (new FileInputStream ("Examplea.xml")); Add a processing instruction processinginstruction pi = new ProcessingInstruction ("Xml-stylesheet", "href=\" booklist.html.xsl\ "type=\" Text/xsl\ ""); Doc.addcontent (PI); Element root = Doc.getrootelement ()//Get root element java.util.List books = Root.getchildren ()//Get the collection element of all child elements of the root elementBook = (Element) books.get (0);  Get the first book element//Add a property to the first one = new attribute ("Hot", "true"); Book.setattribute (a); Element author = book.getchild ("author"); Gets the specified Word element author.settext ("Harry"); Change the author to Harry//or Text t = new text ("Harry"); Book.addcontent (t); Element price = Book.getchild (' price ');//Get the specified Word element//modify prices, the more depressing thing is that we have to transform the data type ourselves, which is the advantage of JAXB Author.settext (  Float.tostring (50.0f)); String indent = ""; Boolean newlines = true; Xmloutputter OUTP = new Xmloutputter (indent,newlines, "GBK"); Outp.output (Doc, New FileOutputStream ("Exampleb.xml"));};
       


Execution Results Exampleb.xml:

       
        
         
        <?xml version= "1.0" encoding= "GBK"?><booklist> <book hot=    "true" >        Introduction to Programming for <name>java </name>        <author>50.0</author>        <publishDate>2002-6-6</publishDate>        <price>35.0</price>    </book>    <book>        <name>xml application in Java </name >        <author> Dick </author>        <publishDate>2002-9-16</publishDate>        <price >92.0</price>    </book></booklist><?xml-stylesheet href= "bookList.html.xsl" type= " Text/xsl "?>
       
        


By default, methods such as the GetText () of the Jdom element class do not filter whitespace characters, if you need to filter, with Settexttrim ().

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.