Simplify XML programming with JDOM

xiaoxiao2021-03-18  189

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.

Mark: Java and XML

In many ways, Java language has 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 for XML standard planning document object model

Org.xml.sax, an easy API for event drivers for syntax analysis of XML

Javax.xml.Parsers, factory tools, allow application developers to 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 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, 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 JDOM documentation

JDOM uses 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 information to download the full code of this article) List 1. Establish an XML document sample

Toyota

Celica

1997

Green

1ABC234

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");

CARELEMENT.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). 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 ();

Collaborate with other methods: interoperability with existing XML tools

An interesting feature of JDOM 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 for 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

<xsl: value-of select = "make" /> <xsl: value-of select = "mod) /></p> <p></ hEAD></p> <p><body></p> <p><H1> <XSL: Value-of Select = "Make" /> </ h1> <br /></p> <p><H2> <XSL: Value-of Select = "Model" /> </ h2> <br /></p> <p><Table Border = "0"></p> <p><TR> <TD> VIN: </ TD> <TD> <xsl: value-of select = "@ VIN" /> </ td> </ tr></p> <p><Tr> <TD> Year: </ TD> <TD> <XSL: Value-of Select = "Year" /> </ td> </ tr> <tr> <td> color: </ td> <TD > <xsl: value-of select = "color" /> </ td> </ tr></p> <p></ TABLE></p> <p></ body></p> <p></ html></p> <p></ xsl: template></p> <p></ xsl: stylesheet></p> <p>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.</p> <p>Listing 14. Creating an HTML document using JDOM and Xalan</p> <p>TransformerFactory Tfactory = TransformerFactory.newInstance ();</p> <p>// make the input sources for the xml and xslt documents</p> <p>Org.jdom.Output.domOutputter outputter = new Org.jdom.Output.domOutputter ();</p> <p>Org.w3c.dom.document domdocument = outputter.output (myDocument);</p> <p>Javax.xml.transform.Source Xmlsource =</p> <p>New javax.xml.transform.dom.domsource (DomDocument);</p> <p>Streamsource xsltsource =</p> <p>New streamsource (New fileInputStream ("/ some / directory / car.xsl");</p> <p>// make the output result for the finished document sale</p> <p>// the httpresponse outputstream</p> <p>StreamResult XmlResult = new streamResult (response.getOutputStream ());</p> <p>// Get a xslt transformer</p> <p>Transformer Transformer = TFactory.NewTransformer (xsltsource);</p> <p>// do the transform</p> <p>Transformer.Transform (Xmlsource, XmlResult);</p> <p>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.</p> <p>Sun and JDOM: What is the name in the name?</p> <p>JDOM's 1.0 formal release may match it in the intertility direction in Java Community Process. The JDOM submitted by JSR-102 has been approved to become the ultimate containing part of the core Java platform. Sun's evaluation is: "JDOM is indeed easier to use than the early API, so we believe that it will become an additive for Java platform." According to JSR, the package of JDOM 1.0 issued may by "Org.jdom) "Change" javax.xml ". Despite the optimism, developers may eventually change their code to use new code.</p> <p>JDOM growth: a glimpse of the foreground</p> <p>As mentioned in this article, the JDOM project has released its Beta 6 version. Even in the Beta state, JDOM has proven to be a stable for implementation methods in many real worlds. Although most of the APIs have been stable, some work is still working on existing interfaces in some areas. Therefore, at this point, any development items in progress do not need to avoid JDOM because it is afraid of a mistake, but it is necessary to consider the fact that some method structures or some semantics may still be released and Changes before being used by the core Java API. (See what is included in the name?)</p> <p>JDOM followed by the commitment to stabilize API and evaluate performance issues in all aspects of implementation. Other aspects have progressed, but it also causes hindrance to some application developers, including supporting DTD entities and other less common constructions. Further, further integrate XML data sources for XPath (which is an XML path language that is unique to XSLT).</p> <p>So, ahead, is JDOM better than the existing XML API? If you dream Java, that answer may be "yes". Jdom does not mean that you will replace your favorite grammar or XML sensitive database, but its design principles help to provide fast learning paths for new and old Java developers trying to master XML worlds.</p> <p>Reference</p> <p>Please download the sample code (a source code version of the Java class and the compiled version, including all sample code used herein and XML and XSL files). You will need to run the code in JDOM, Xerces, and Xalan in the classpath. For the latest version of JDOM, online API documents and more, please visit the JDOM website.</p> <p>For more information on Xalan, Xerces and other Java XML products, please visit the Apache XML website.</p> <p>Please visit the XML website to get general XML information, tutorials, and resources.</p> <p>Please don't forget the developerWorks XML area, there is a large amount of content related to XML.</p> <p>IBM's AlphaWorks website provides several tools for Java and XML developers:</p> <p>XML Parser for Java contains disclosure and stable support for the DOM level 1 and SAX level 1 specification.</p> <p>In order to diagnose the incorrect use of the XML Schema language, try XML Schema Quality Checker.</p> <p>XML Security Suite provides a variety of security features such as digital signatures, element-type encryption, and access control.</p> <p>Use XSL Editor to test and edit your XSL.</p> <p>IBM XML Parser for Java (XML4J) is a convenient tool for controlling an XML document. "Use IBM XML Analyzer" to teach you its usage. (IBM PartnerWorld For Developers, January 2000)</p> <p>JDM's creators are well-known writers. We recommend you to read Jason Hunter's "Java Servlet Programming, 2nd Edition" (O'Reilly, "Java and XML" in Brett McLaughlin (O'Reilly, June 2000).</p> <p>In addition, the following is a few related articles written by Brett for developerWorks:</p> <p>"From DOM Conversion" (April 2001)</p> <p>"From SAX Conversion" (April 2001)</p> <p>"Using JDOM and XSLT" (March 2001)</p> <p>"Everything about JAXP" (November 2000)</p> <p>"JAXP Revision" (December 2000)</p> <p>"Control DOM" (DeveloperWorks, April 2001) written by William Phillips and Gary Cole) introduces DirectDom to Java developers.</p> <p>Please participate in the developerWorks XML tool and API discussion for Java developers.</p> <p>There are more information about using DOM to integrate XML documents into the application.</p> <p>See how MEGOBJECTEXAMPLUGIN will convert the web page to the "Low Media" page.</p> <p>About author</p> <p>WES BIGGS has developed Internet applications for some companies including Los Angeles Times, USWeb and Elite Information Systems. He often writes an open source Java project and maintains a regular release package of Gnu.Regexp of the Free Software Fund. You can contact WES@tralfamadore.com.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-129974.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="129974" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.040</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'AJi4d5g95aEbQ5cGaqhepnOaZzv2uyBnLIlvcEIUlR5eCs6_2BrfsKa_2BGYszckIgY4XhOtlkv_2Fqu_2FSMTiE'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>