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 tools for XML standard planning document object models, ORG.XML .sax, the simple API Javax.xml.Parsers, factory tools, which are used for syntax analysis of XML, allowing application developers to get and configure special syntax analyzer tools, although for Java developers, there is These packages are a good thing, but it only represents a formal license for the 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 the founding results of two famous Java developers, Brett McLaughlin and Jason Hunter. In early 2000, JDOM officially began to develop, JDom as an open source project. Officially started.
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, we must consider the limitations of W3C DOM design: language independence. 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 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 material to download the full code of this article) List 1. Establish an XML document sample XML Version = "1.0" encoding = "UTF-8"?>
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 property: Listing 3. Add an Attribute Carelement.setttribute ("VIN", "123FHG5869705IOP90"); adding elements are also very simple. Here we add Make Elements: Listing 4. Elements and child elements
Element make = new element ("make"); make.addContent ("Toyota"); calement.addcontent (opportunity); Because Element's AddContent method returns ELEMENT, we can also write: Listing 5. Add element Carelement with simple form .addContent (New Element ("Make"). 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
CAREMENT.ADDCONTENT (New Element ("Celica"); Carelement.addContent (New Element ("Year"); AddContent ("1997")); Carelement.AddContent (New Element " ) .addContent ("green"))); Carelement.addContent (New Element ("License") .addContent ("1ABC234"). Addattribute ("State", "CA")); you will notice that for license elements, we Not only added elements, but also adds an attribute 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: Listing 7. Add a note (New Comment ("Description of a car"); operational document is also using a similar way. For example, to quote Year elements, we use Element's getChild method:
Listing 8. Access child elements
Element Yerelement = CAREMENT.GETCHILD ("YEAR"); this statement will actually return the first element name 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. In a similar way, we can remove the Year elements from the document: List 9. Remove sub-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 JDOM XMLOUTTER Class: Listing 10. Translate JDOM to XML text try {xmloutputter outputter = new xmloutputter (", true); 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 (); Good collaboration with other methods: interoperability with existing XML tools JDOM An interesting feature 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 (NullPointerException e) {E.PrintStackTrace ();} You can operate the document created through this process with the way you display 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 table called Car.xsl: Listing 13. XSL document for converting car records to HTML
XML Version = "1.0" encoding = "UTF-8"?> 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 using // the HTTPResponse OutputStream StreamResult xmlResult = new StreamResult (response.getOutputStream ()); // Get a XSLT transformer Transformer transformer = tFactory.newTransformer (xsltSource); // Do The Transform Transform Transform Transform (Xmlsource, XmlResult); In this example, the output is out of the HTTPRESPONSE OUTPUTSTREAM with 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.
< Table border = "0"> vin: td> Year: td> color: td>