Simplify XML programming with JDOM

xiaoxiao2021-03-06  63

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 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. Create 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 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

<xsl: value-of select = "make" /> <xsl: value-of select = "model" /> </ head> <body > <H1> <xsl: value-of select = "make" /> </ h1> <br /> <xsl: value-of select = "model" /> </ h2> <br /> < Table border = "0"> <tr> <td> vin: </ td> <td> <xsl: value-of select = "@ VIN" /> </ td> </ tr> <tr> <td> Year: </ td> <TD> <xsl: value-of select = "year" /> </ td> </ tr> <tr> <td> color: </ td> <td> <xsl: value- Of select = "color" /> </ td> </ tr> </ table> </ body> </ html> </ xsl: template> </ xsl: styleSheet> Now we will convert Org.jdom.Document For the Dom Document and supplies it with files that display our XSL and OutputStream to Xalan, OutputStream is obtained from the application server we assume a servlet (such as Listing 14). Listing 14. Creating an HTML document using JDOM and Xalan</p> <p>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.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-110965.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="110965" 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.042</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 = 'RHtvJHiQhUuA9do0gj_2BZq3HmDM4DYEis3zTYLopDEPq_2BZfGeR2lNUFqf1nVhEpzeHmPkmC03Tnn8FYBUpO_2FQag_3D_3D'; 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>