Reprinted: http://www-900.ibm.com/developerWorks/cn/java/j-jdom/index.shtml
JDOM is an unique Java kit for quickly to quickly develop XML applications. Its design contains the syntax of the Java language and even semantics. But is it better than the existing - more standard - XML API? When we have seen some examples and explain the design goals of this popular open source project, you can judge it. Recently, this open source code project has been officially accepted as a Java specification requirement.
As a developer, you may have heard of 80-20 rules, in other areas, known as Pareto rules: a process or method can accommodate 80% of all possible situations, and 20% need to be processed according to specific situations. The inevitable result of software development is: For developers, it is very easy to complete 80% of the work that may be done after a given technology.
Of course, software products and standards are not always developed according to 80-20 rules. In particular, the shortcomings of Java XML are an exception to this rule. Java's programming world has a lot of API - some are developed by themselves, some of which are developed by several large companies - they provide a mature solution to resolving special XML tasks. As a certificate of XML universality, there is a new technique for each new task, but how to combine them together, how to find an appropriate tool to complete 80% of the task that must be repeated - using Java Basic XML tree operation for the language of the language? JDOM is just an XML API used to solve the above problems.
Marks: Java and XML In many ways, Java languages have become a programming language for XML selection. Due to the pioneering work made by the Apache Software Foundation and IBM AlphaWorks, there is now a complete tool chain for creation, operation, transfer document, and grammar analysis of XML documents.
However, although many Java developers are using XML every day, Sun is behind the XML into the Java platform. Because XML has become a key technique from the merchant to the merchant to integrate the content of the web site content, the Java 2 platform is very popular. Sun has used JSR procedures to make it an existing XML API's nasal ancestor, which has been widely accepted. At present, the most significant joined JAXP (Java API for XML syntax analysis), which contains three packages:
Org.w3c.dom, W3C recommended Java tool ORG.XML.SAX for XML standard planning document object model, is used to use XML's syntax analysis of event-driven simple API Javax.xml.Parsers, factory tools, allowed Application developers get and configure special syntax analyzer tools
Although for Java developers, these packages are good things, but it only represents a formal license for existing API standards, and has not yapped in terms of providing first-class Java-XML interoperability. The core Java platform is lacking is an intuitive interface that uses XML documents as a Java object operation.
Enter JDOM. Jdom is two famous Java developers, Brett McLaughlin and Jason Hunter's creation results.
At the beginning of 2000, JDom officially began to develop as an open source project, and JDom officially started as an open source code project. It has grown into systems that contain contributions, centralized feedback, and wrong repair from a wide range of Java developers, and is committed to establishing a complete Java platform-based solution, access, operation and output XML data through Java code. This is a suitable API for JDOM, and the dumb JDOM can replace the org.w3c.dom package to operate XML documentation. It is not a simple alternative, in fact, Jdom and DOM can be more comfortable. In addition, although the package it provides is a large amount of work in the package from the configuration and run analyzer, it is not responsible for grammar analysis of XML according to the text input. JDom is based on the ability of the existing API, as "a better mousetrap" expressed by the project page.
To understand the reasons for the need for alternate APIs, consider the limitations of W3C DOM design:
Language is independent. Dom is not designed in Java language in people's minds. Although this approach retains very similar APIs in different languages, it also makes the programmers who are used to java language feel more troublesome. For example, a String class has built in the Java language, and the DOM specifies its own Text class. Strict hierarchy. The DOM API directly hits the XML specification. In XML, each thing is a node, so you can find a Node-based interface that can be extended in the DOM and returns a series of methods that returns NODE. In terms of polymorphism, it is excellent, but in view of the interpretation, it is difficult and inconvenient in the Java language, where explicit pull from Node to the leaf type will cause the length and difficult to understand the code. . Interface driver. The public DOM API is only composed of interfaces (Exception class is an exception, but it is precise enough). W3C is not interested in providing implementation, it is only interested in defining interfaces (more meaningful). But it also means that as a Java programmer uses the API to add a dispersion when creating an XML object, because the W3C standard uses a large number of factory-based classes and similar flexible but inadvertent patterns. In some applications, the XML document is built only by the syntax analyzer, and never created by the application level code, which is not related. However, as XML is more widely used, not all issues continue to be driven by a grammar analyzer. The developer of the application needs a more convenient way to construct an XML object.
For programmers, these constraints means that the API, learning and use of the memory occupancy and interface size) is difficult. In contrast, JDOM is made as a lightweight API, the most important thing is that it is centered on Java. It removes the above disadvantages on the basis of following the main rules of the DOM:
JDOM is dedicated to the Java platform. As long as it is possible, the API uses the built-in String support of the Java language, so the text value is also available for String. It also uses the Java 2 platform class, such as List and Iterator, providing programmers with a rich and similar environment with Java languages. There is no hierarchy. In JDOM, the XML element is an instance of ELEMENT. The XML property is an instance of Attribute, and the XML document itself is the instance of Document. Since all of this represents different concepts in XML, they always be referenced as their own type, not as a vague "node." Class driver. Because JDOM objects are direct instances such as Document, Element, and Attribute, create a new JDOM object as easy as the New operator is used in Java language. It also means that it is not necessary to make a factory interface configuration - JDOM is straightforward. Look, no node: Establish and operate the JDOM document JDOM uses the standard Java encoding mode. As long as it is possible, it uses Java New operators without complicated factory modes to make object operations even convenient for beginner users. For example, let's take a look at how to create a simple XML document with JDom. The structure we will build is as shown in Listing 1. (From the reference, download the full code of this article)
Listing 1. Establish an XML document sample
XML Version = "1.0" encoding = "UTF-8"?>
car>
Note: We will establish an example document, which is described in detail in Listing 2 below.
Start, let's create a root element first and add it to the document:
Listing 2. Creating a Document
Element Carelement = New Element ("car");
Document myDocument = new document (CARELEMENT);
This step creates a new Org.jdom.Element and uses it as the root element of Org.jdom.Document MyDocument. (If you use the sample code provided in the reference information, be sure to import org.jdom. *.) Because an XML document must have a unique root element, the document puts Element in its constructor.
Next, add a VIN attribute:
Listing 3. Add an Attribute
CARELEMENT.ADATTRIBUTE (New Attribute, "123FHG5869705IOP90"));
Adding elements is also very simple. Here we add Make Elements:
Listing 4. Element and child elements
ELEMENT MAKE = New Element ("Make");
Make.addContent ("Toyota"); CAREMENT.ADDCONTENT (MAKE);
We can also write this because Element's AddContent method returns Element.
Listing 5. Adding elements in a simple form
CARELEMENT.ADDCONTENT (New Element). AddContent ("Toyota");
These two statements have completed the same job. Some people think that the first example readability is better, but if you build a lot of elements at a time, you will feel that the second example readability is better. To complete the build document:
Listing 6. Add the rest of the elements
CARELEMENT.ADDCONTENT (New Element ("model"). AddContent ("Celica"));
CARELEMENT.ADDCONTENT (New Element ("Year"). AddContent ("1997"));
CARELEMENT.ADDCONTENT (New Element ("color"). AddContent ("Green"));
CARELEMENT.ADDCONTENT (New Element ("License")
.addContent ("1ABC234"). Addttribute ("State", "CA"));
You will notice that for the License element, we not only add an element, but also add a property to it, indicating that the license has been issued. This is because Element's AddContent method always returns Element itself, not an invalid statement.
Add a comment section or other standard XML type with the same method:
Listing 7. Add a comment
CARELEMENT.ADDCONTENT (New Comment ("Description of a car");
Operating documents is also similar to a similar way. For example, to quote Year elements, we use Element's getChild method:
Listing 8. Access child elements
Element YereElement = CARELEMENT.GETCHILD ("YEAR");
This statement will actually return the first element names YEAR. If there is no Year element, the call returns an empty value. Note that we don't have to go back to the return value similar to the DOM Node interface - the child element of Element is Element. With a similar way, we can remove the Year elements from the document:
Listing 9. Remove child elements
Boolean Removed = CARELEMENT.RemoveChild ("Year");
This call will only remove the Year Element; the rest of the document remains unchanged.
So far, we have covered the generation and operation of the document. To output the completed document to the console, you can use the XMLOUTTER class of JDOM:
Listing 10. Convert JDOM to XML text
Try {
XMloutPutter Outputter = new xmloutputter (",);
Outputter.Output (MyDocument, System.out);
} catch (java.io.ioException e) {
E.PrintStackTrace ();
}
XMloutPutter has several format options. Here we have specified that the desired child elements are indented from the parent elements from two spaces, and there is a blank line between the elements. XMLOUTPUTTER can output to Writer or OutputStream. To output to the file, we can simplify the output line to: Listing 11. Output XML using FileWriter
FileWriter Writer = New FileWriter ("/ some / Directory / MyFile.xml);
Outputter.Output (MyDocument, Writer);
Writer.close ();
Collaboration with other methods: An interesting feature of interoperability with existing XML tools is interoperability with other APIs. Using JDOM, not only outputting documents to Stream or Reader, but also document as Sax Event Stream or as Dom Document. This flexibility allows JDOM to be used or added to a system that has been processed using another method to process XML. As we saw in an example in the later example, it also allows JDOM to use other XML tools that have not been able to identify JDOM.
Another use of jdoms is that it can read and operate existing XML data. Use a class in Org.jdom.Input to read the structure of the XML file that is very specified. In this example we use Saxbuilder:
Listing 12. Syntax analysis using SaxBuilder to XML files
Try {
Saxbuilder Builder = new saxbuilder ();
Document anotherdocument =
Builder.Build (New File ("/ some / directory / sample.xml");
} catch (jdomexception e) {
E.PrintStackTrace ();
} catch (nullpointersexception e) {
E.PrintStackTrace ();
}
You can operate the document established through this process with the method you are displayed in Listing 2 to Listing 7.
Another practical application of Jdom combines it with Apache's Xalan products (see Resources). Using the above car example, we will create a web page for the online car dealer, showing details of a specific car. First, assume that our document we have set up is displayed in the information we prepare to present the user's car. Next, we will combine this Jdom Document with an XSL style sheet and output the result of the HTML format to the servlet's OutputStream to display in the user's browser.
In this example, we are ready to use the XSL style sheet called Car.xsl:
Listing 13. XSL document for converting car records to HTML
XML Version = "1.0" encoding = "UTF-8"?>
table>
body>
html>
xsl: template>
xsl: stylesheet>
Now we will convert Org.jdom.Document to Dom Document, and provide it with files that display our XSL and OutputStream to Xalan, OutputStream is our application server we use servlet (as shown in Listing 14) Get it.
Listing 14. Creating an HTML document using JDOM and Xalan
TransformerFactory Tfactory = TransformerFactory.newInstance ();
// make the input sources for the xml and xslt documents
Org.jdom.Output.domOutputter outputter = new Org.jdom.Output.domOutputter ();
Org.w3c.dom.document domdocument = outputter.output (myDocument);
Javax.xml.transform.Source Xmlsource =
New javax.xml.transform.dom.domsource (DomDocument);
Streamsource xsltsource =
New streamsource (New fileInputStream ("/ some / directory / car.xsl");
// make the output result for the finished document sale
// the httpresponse outputstream
StreamResult XmlResult = new streamResult (response.getOutputStream ());
// Get a xslt transformer
Transformer Transformer = TFactory.NewTransformer (xsltsource);
// do the transform
Transformer.Transform (Xmlsource, XmlResult);
In this example, the output is out of HttpResponse OutputStream through the Java Servlet. However, the output stream can be as simple as the instance using XMLOUTPUTTER as simple as an instance of XMLOUTPUTTER. We use DomoutPutter to generate an XML source code for Xalan. But we can generate the same output, and the method is to output our XML documents as String using XMLOUTPUTTER and enters streamsource. Speaking of flexibility: JDOM can output its structure as String, SAX Event Stream or Dom Document. This allows JDOM to work with any of these models as an input tool. (With regard to additional features, please visit the JDM Web site, where you will find a treasure gallery based on JDM tools to provide JDBC ResultSet builder, XPath implementation methods and other tools.) In just a few lines In the code, JDOM enables many functions, we have analyzed the XML documents in XML, and operate those documents and use them to generate XML-driven web pages.