JDOM Introduction and Use Guide

Source: Internet
Author: User
Tags api manual cdata gettext processing instruction xslt
Dom
Turn from: http://blog.csdn.net/hk2000c/archive/2003/09/26/15239.aspx

JDOM Introduction and Use Guide

Introduction to JDOM JDOM is an open source project, which is based on a tree structure, using pure Java technology to parse, generate, serialize, and manipulate XML documents. JDOM directly for Java programming services. It leverages the many features of the more powerful Java language (method overload, set concepts, and mappings) to effectively combine the functionality of Sax and DOM. Hide the complexity of the original XML process as much as possible with the design. Using Jdom to process XML documents is easy and easy. 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 largely due to the fact that SAX does not have document modification, random access, and output functionality, and for DOM, Java programmers are often less comfortable to use when used. The main disadvantage of DOM is that because DOM is an interface Definition language (IDL), its task is one of the lowest common standards in different language implementations, and is not specifically designed for Java. The latest version of Jdom is Jdom Beta 9. The recent jdom has been included in the JSR-102, marking Jdom as part of the Java platform.

Second, the JDOM package Overview JDOM is composed of the following packages Org.JDOMorg.JDOM.inputorg.JDOM.outputorg.JDOM.adaptersorg.JDOM.transform

Iii. description of the JDOM class

Org. Jdom the class in this package is all the data types you use to parse the XML file. Attributecdatacomentdoctypedocumentelemententityrefnamespaceproscessinginstructiontext

Org. Jdom.transform should use the following 2 classes when it comes to XSLT format conversions Jdomsourcejdomresult

Org. Jdom.input input class, commonly used for document creation Saxbuilderdombuilderresultsetbuilder

Org. Jdom.output output class, for document conversion output Xmloutputtersaxoutputterdomoutputterjtreeoutputter

Pre-use Precautions: 1. Jdom support for JAXP and TRax jdom support JAXP1.1: You can use any Parser tool class in your program, and by default, JAXP parser. The development of special parser can be saxbuilder parser = new Saxbuilder ("Org.apache.crimson.parser.XMLReaderImpl") in the following form; Document doc = Parser.build ("http://www.cafeconleche.org/"); Work with the document ... JDOM also supports trax:xslt through Jdomsource and Jdomresult classes (see chapters later) 2. Note that the document class in JDOM is represented by Org.JDOM.Document. This is different from the document in Org.w3c.dom, and how these 2 formats are converted will be explained later. The following, if not specified, refers to the document in Jdom.

Iv. Jdom main methods of Use 1.Ducument Class (1) Document operation method: Element root = new Element ("greeting");D ocument doc = new Document (root); Root.settext ("Hello jdom!"); or simply use document DOC = new document (New Element ("greeting"). SetText ("Hello jdom!t"));

This is different from DOM. DOM requires more complex code, as follows: Documentbuilderfactory factory =documentbuilderfactory.newinstance ();D Ocumentbuilder builder = Factory.newdocumentbuilder ();D ocument doc = Builder.newdocument (); Element root =doc.createelement ("root"); Text text = Doc.createtext ("This is the root"); Root.appendchild (text);d oc.appendchild (root);

Note: Jdom does not allow the same node to be associated with 2 or more documents at the same time, to use nodes in the original old document in document 2nd. First you need to use detach () to separate this node. (2) Get Document object from file, stream, System ID, url: dombuilder builder = new Dombuilder ();D ocument doc = builder.build (new file ("Jdom_ Test.xml "));

Saxbuilder builder = new Saxbuilder ();D ocument doc = builder.build (URL); Dombuilder has been deprecated in the new version. Dombuilder.builder (URL), with sax efficiency will be faster.

Here's a small example of using a string object directly as an XML data source for the sake of simplicity:

 public jdomtest () {    String textxml = null;    textxml = "<note>";  & nbsp;  textxml = Textxml +        "<to>aaa</to><from>bbb </from>
It's a simple move.

(3) The conversion between Dom's document and Jdom's document is simple! Dombuilder builder = new Dombuilder (); Org.jdom.Document jdomdocument = Builder.build (DOMDocument);//work with the Jdom do Cument ...

Domoutputter converter = new Domoutputter (); Org.w3c.dom.Document DOMDocument = Converter.output (jdomdocument);//Work With the DOM document ...

2.XML Document output Xmloutputter class: Jdom output is very flexible, support many kinds of IO format 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 (""); o Utp.setnewlines (True); Outp.output (Doc, System.out); See the latest Jdom API manual for details

3.Element class: (1) Browse the element tree/get the root element elementelement root = Doc.getrootelement ();//Get a listlist of all child elements Allchildren = Root.getchildren ()///obtains the listlist Namedchildren = Root.getchildren ("name") of the specified name child element;//Gets the first child element of the specified name, Root.getchild ("name"); (the List here is Java.util.List)

Jdom gives us a lot of very flexible use methods to manage the child element list Allchildren = Root.getchildren ();//delete the fourth child element Allchildren.remove (3);/delete Call "Jack." The child element Allchildren.removeall (Root.getchildren ("Jack"));

Root.removechildren ("Jack"); Easy to spell//join Allchildren.add (New Element ("Jane"));

Root.addcontent (New Element ("Jane")); Convenient writing allchildren.add (0, New Element ("a");

(2) Mobile elements: very simple in jdom element movable = new Element ("movable");p arent1.addcontent (movable); Placeparent1.removecontent (movable); Removeparent2.addcontent (movable); Add

In DOM element movable = doc1.createelement ("movable");p arent1.appendchild (movable); Placeparent1.removechild (movable); Removeparent2.appendchild (movable); Error!

Add: The element constructor for error-correcting jdom (and its other functions) checks whether the element is legitimate. And its Add/remove method will check the tree structure, check the contents as follows: 1. Is there a link point 2 in any tree? Whether there is only one root node 3. Is there a consistent namespace (namespaces)



(3) element's text content read <description>a cool demo</description>

The text is directly available//Returns "\ A cool demo\n" String desc = Element.gettext ();

There ' s a convenient shortcut//Returns "a cool demo" String desc = Element.gettexttrim ();

(4) Elment Content Modification Element.settext ("A new description"); 3. Can correctly interpret special characters element.settext ("<xml> content"); 4.CDATA data writes, Read out element.addcontent (new CDATA ("<xml> content")); String nodifference = Element.gettext ();

A mixed content element may contain a variety of content, such as

<table><!--Some Comment-->some text<tr>some child element</tr></table>

Takes the child element of the table trstring Text = Table.gettexttrim (); Element tr = table.getchild ("tr");

You can also use another simpler method list Mixedco = Table.getcontent (); iterator ITR = Mixedco.iterator (); while (Itr.hasnext ()) {Object o = i.ne XT (); if (o instanceof Comment) {...} This can be written as comment, Element, Text, cdata,processinginstruction, or EntityRef type}//Now remove comment, note that the cursor should be 1. This is because the ENTER key is also parsed into the text class, so the comment entry should be 1. Mixedco.remove (1);



4.Attribute class <table width= "100%" border= "0" > </table>//obtained attributestring width = table.getattributevalue ( "width"); int border = Table.getattribute ("width"). Getintvalue ();//Set Attributetable.setattribute ("Vspace", "0"); Delete one or all Attributetable.removeattribute ("vspace"); Table.getattributes (). Clear ();



5. Processing instruction (processing instructions) operates an example of pls <?br?><?cocoon-process type= "xslt"?> |          |        |        | Target data

Processing target name (target) String target = Pi.gettarget (), all data is obtained, all data after Target is returned. String data = Pi.getdata (); Gets the data string type = Pi.getvalue ("type") of the specified property; Gets the name list ls = Pi.getnames () of all properties;

6. Namespace operations <xhtml:html xmlns:xhtml= "http://www.w3.org/1999/xhtml" ><xhtml:title>home page</xhtml: Title></xhtml:html>

Namespace xhtml = Namespace.getnamespace ("xhtml", "http://www.w3.org/1999/xhtml"); List kids = Html.getchildren ("title", XHTML); Element kid = html.getchild ("title", XHTML); Kid.addcontent (New Element ("table", XHTML);

7.XSLT format conversion Use the following function to convert to XSLT finally if you need to use the document of the consortium 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 (TransformerException 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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.