Working with XML documents with Jdom

Source: Internet
Author: User
Tags filter cdata comparison documentation processing instruction versions web services xsl
Dom|xml reproduced in cnjsp.com.
Author: ayellow [2002-04-09]
Keywords: Java, JDOM, XML, JAXB
Welcome to discuss with me (boyofjava@sina.com)


(i) Introduction of 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 this year (2002), 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, cannot write processing instructions to XML documents, and sometimes we need to preserve line breaks and trailing spaces that are automatically filtered out in Jaxb, even in <! [cdata[and]]> are not spared. 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.


(ii) Acquisition and installation of 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.


(c) 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> Introduction to         <name>java Programming </name>         <author> John </author>        < publishdate>2002-6-6</publishdate>        <price>35.0 </price>    </book>    <book>    The application of      <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 ();         //constructs a document from a file because the encoding is already specified in the XML file, so there's no need to          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 (); Gets the set of all child elements of the root element         element book = (Element) books.get (0); Get the first book element         //add a property to the first one          attribute a = 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"); To get the specified Word element         //modify the price, 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" > <name>java programming Entry </name > <author>50.0</author> <publishDate>2002-6-6</publishDate> <price>3 5.0</price> </book> <book> <name>xml application in Java </name> <author> dick ;/author> <publishDate>2002-9-16</publishDate> <price>92.0</price> &LT;/BOOK&G T;</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 ().



(iv) Reference documentation

1) JDOM makes XML Easy (http://www.servlets.com/speaking/jdom-javaone.pdf)
2) The java™architecture for XML Binding User ' s Guide (http://java.sun.com/xml/jaxb/jaxb-docs.pdf)
3 Web Services Made easier. The Java TM APIs and architectures for XML, A technical white Paper (http://java.sun.com/xml/webservices.pdf)

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.