Make XML programming more simple - JDOM introduction and programming guide

zhaozj2021-02-16  52

Jdom introduction and use guide

First, JDM introduction JDOM is an open source project, which is based on the tree structure, using pure Java technology to resolve, generate, serialize, and multiple operations for XML documents. JDOM is directly programmed for Java. It utilizes more features of more powerful Java languages ​​(method overload, collection concepts, and mapping), effectively combining SAX and DOM functions. Hide the original use of the XML process as designed to use the complexity of the XML process. Using JDOM to handle XML documents will be a relaxed, simple matter. JDOM was developed by Brett McLaughlin and Jason Hunter in the spring of 2000 to make up for the shortcomings of Dom and SAX in practical applications. These deficiencies are mainly in SAX no document modification, random access, and output, and for DOM, Java programmers will always be very convenient to use. Dom's shortcomings are mainly derived from DOM is an Interface Definition Language (IDL). Its task is a minimum general standard in different language implementations, not specially designed for Java. The latest version of JDOM is JDOM Beta 9. Recently, JDOM is included in JSR-102, which marks a part of JDOM a Java platform.

Second, the JDOM package overview JDOM is made of org.jdomorg.jdom.inputorg.jdom.jdom.inputorg.jdom.Outputorg.jdom.Adaptersorg.jdom.jdom.Adaptersorg.jdom.jdom.Adaptersorg.jdom.jdom.Adaptersorg.jdom.jdom.Adaptersorg.jdom.jdom.Adaptersorg.jdom.jdom.Adaptersorg.jdom.jdom.Adaptersorg.jdom.jdom.Adaptersorg.jdom.transform

Third, JDOM class description

Org.jdom This package is the type of data you want to use after you resolve the XML file. AttributeCDataComentDoctypedocumentElemenTentityRefNamespaceProscessinginstructionText

Org.jdom.Transform should use the following 2 class JDomsourcejDomResult when transitioning to XSLT format.

Org.jdom.Input Enter the class, generally used for the creation of the document SAXBuilderDombuilderResultSetBuilder

Org.jdom.output output class for document conversion output XMLOUTPUTTERSAXOUTPUTTOUTPUTTERJTREEOUTPUTTER

Precautions Preview: 1.jdom For JAXP and TRAX support JDOM support JAXP1.1: You can use any Parser tool class in the program, by default, JAXP Parser. Develop special Parser available SAXBUILDER PARSER = New Saxbuilder ("org.apache.crimson.Parser.xmlReaderImpl"); document doc = parser.build ("http://www.cafeconleche.org/"); // Work With the document ... JDOM also supports Trax: XSLT can be converted through JDomSource and the JDomResult class (see later chapter) 2. Note that in the JDom documentation (Document) class is represented by org.jdom.document. This is to distinguish between Document in org.w3c.dom, how these two formats are converted later. The following is as not specifically referred to as Document in the JDOM.

Fourth, JDOM main use method 1. Cucle class (1) Document method: element root = new element ("greeting"); document doc = new document (root); root.settext ("Hello Jdom!"); Or Simple Using Document Doc = New Document ("Greeting"). SetText ("Hello Jdom! T")); this is different from DOM. Dom will need more sophisticated code, as follows: DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance (); DocumentBuilder builder = factory.newDocumentBuilder (); Document doc = builder.newDocument (); Element root = doc.createElement ( "root"); Text text = doc.createtext ("this is the root"; root.appendchild (text); doc.appendchild (root);

Note: JDOM does not allow the same node to be associated with 2 or more documents, and use the original old document in the second document. First, you need to use DETACH () to separate this node. (2) Get the document, stream, system ID, and URL to get Docuilder Builder = New Dombuilder (); Docuild Doc = Builder.Build (New File ("jdom_test.xml");

SAXBUILDER Builder = new saxbuilder (); document doc = builder.build (URL); Dombuilder has deprecated DomBuilder.builder (URL) in the new version, using SAX efficiency.

Here is a small example. For the sake of simplicity, use String objects directly as an XML data source:

Public jdomtest () {string textXML = null; TextXML = ""; TextXml = TextXml " aaa bb ccc DDD "; TextXML = TEXTXML " "; Saxbuilder Builder = New Saxbuilder (); document doc = null; Reader IN = New stringReader (TEXTXML); try {doc = builder.build (in) Element root = doc.getrootElement (); list ls = root.getchildren (); // Note About this ELEMENT collection for the root node below (Iterator Iter = ls.Itemrator (); it.hasnext ();) {ELEMENT EL = (ELEMENT) ore.next (); if (El.getName (). Equals ("to")) {system.out.println (el.getText ());}}} catch (OoException ex) {ex.printStackTrace ();} catch (jdomexception ex) {ex.printstacktrace ();}} is simple.

(3) DOM's Document and JDOM Document mutual conversion method, simple! Dombuilder Builder = New Dombuilder (); org.jdom.document jdomdocument = builder.build (domdocument); // Work with the jdom document ...

DomoutPutter Converter = new domoutputter (); org.w3c.dom.document domdocument = converter.output (jdomdocument); // Work with the document ...

2.XML Document Output XMLOUTPUTTER Class: JDOM's output is very flexible, supporting many IO formats and style output Document Doc = new document (...); xmloutputter outp = new xmloutputter (); // raw outputoutp.output (DOC) , fileOutputStream); // Compressed outputoutp.setTextTrim (true); outp.output (doc, socket.getOutputStream ()); // Pretty outputoutp.setIndent ( ""); outp.setNewlines (true); outp.output (doc , System.out; ...... Please refer to the latest JDOM API manual.

3.Element Class: (1) Browse Element Tree // Get Root ElementElement Root = Doc.GetrooteElement (); // Get all sub-elements of a ListList AllChildren = root.getchildren (); // Get specified name sub-elements Listlist namedchildren = root.getchildren ("name"); // Get the first child element element child = root.getchild ("name") of the specified name; (List here is java.util.list) JDom gave us Many very flexible use methods to manage child elements list allchildren = root.getchildren (); // Delete the fourth child element allchildren.remove (3); // Remove the Subrid of "Jack" Allchildren.Removeall (root.getchildren ("jack"));

Root.removechildren ("jack"); // Convenient write method // Add AllChildren.Add (New Element ("Jane"));

Root.addContent (New Element ("Jane")); // Convenient Writing Allchildren.Add (0, New Element ("first"));

(2) Moving Elements: Simple Element Movable = New Element ("Movable") in JDOM; Parent1.addContent (Movable); // PlaceParent1.RemoveContent (Movable); // RemoveParent2.addContent (Movable); // Add

Element movable = doc1.createElement ("Movable") in DOM; Parent1.Appendchild (Movable); // PlaceParent1.RemoveChild (Movable); // RemoveParent2.Appendchild (movable); // Error!

Supplement: Element constructor of the error correction JDOM (and other functions) will check if ELEMENT is legal. And its Add / Remove method checks the tree structure, the inspection content is as follows: 1. Is there a round-link node in any tree 2. Is there only one root node 3. Is there a consistent namespace (Namespaces)

(3) ELEMENT's Text Content Read a Cool Demo

/// Ret IS Directly Available // Returns "/ N A Cool Demo / N" String Desc = Element.getText ();

// there's a convenient shortcut // returns "a cool demo" string desc = element.gettexttrim ();

(4) ELMENT content modifies Element.Settext ("a new description"); 3. Correctly explain the special character Element.setText (" Content"); 4. CDATA's data writes, read Element.addContent New cdata (" content")); string nodifference = element.getText (); mixed content ELEMENT may contain a lot of content, such as

- Some Comment -> Some Text Some Child Element

Take the child of Table Trstring text = Table.getTextTrim (); Element Tr = Table.GetIld ("TR");

You can also use another simple method List mixedco = table.getContent (); item itR = mixedco.iterator (); while (itr.hasnext ()) {Object o = i.next (); if (o Instanceof Comment ) {...} // This can be written here. (Element, Text, CDATA, Processinginstruction, or type of Entityref)} // Now remove Comment, note that the cursor should be 1. This is because the Enter key is also parsed into a TEXT class, so the comment should be 1. Mixedco.remove (1);

4.attribute class

// Get attributeString width = Table.GetaTributeValue ("width"); int border = table.getattribute ("width"). GetInetValue (); // Set AttributeTable.setttribute ("vSpace", "0"); // Delete one or all AttributeTable.RemoveAttribute ("vSpace"); table.gettributes (). Clear ();

5. Processing Instructions Operating an example of a PLS | | | | Target data

Treatment Target Name (Target) String Target = Pi.getTarget (); Get all data (data), all data after the target (Target) will be returned. String data = pi.getdata (); data string type = pi.getValue ("type") for the specified property; gets all the properties list List ls = pi.getNames ();

6. Name Space Operation Home Page

Namespace.getnamespace ("xhtml", "http://www.w3.org/1999/xhtml"" ethachi1 "," title ", xhtml); element kid = html.getchild (" Title ", XHTML); Kid.AddContent (New Element (" Table ", XHTML)); 7.xSLT Format Conversion Use the following function to convert the XSLT conversion Finally, if you need to use the W3C Document, you need to convert it. public static Document transform (String stylesheet, Document in) throws JDOMException {try {Transformer transformer = TransformerFactory.newInstance () .newTransformer (new StreamSource (stylesheet)); JDOMResult out = new JDOMResult (); transformer.transform (new JDOMSource (in ), out); return out.getdeocument ();} catch (transformerexcection e) {throw new jdomexception ("xslt trandformation failed", e);}}

bibliography:

1.jdom official website: http://www.jdom.org

2. << Processing XML with Java >> Elliotte Rusty Harold 2002

3.jdom API Documentation

4. << jdom makes XML Easy >> Jason Hunter Co-Creator Jdom Project

5.wsdp tutorial

转载请注明原文地址:https://www.9cbs.com/read-27055.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.038, SQL: 9