Jdom the use of detailed and examples

Source: Internet
Author: User
Tags add filter format api manual object gettext string version
Dom| detailed

Introduction of JDOM

Jdom is an open source project that uses pure Java technology to parse, generate, serialize, and manipulate XML documents based on a tree-structured architecture.

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.

Ii. Overview of the JDOM package

Jdom is made up of the following packages
Org.jdom contains all the elements of the XML document Java class

Org.jdom.adapters contains Java classes that fit with the DOM

Org.jdom.filter the filter class that contains the XML document

Org.jdom.input contains classes that read XML documents

Org.jdom.output contains classes to write XML documents

Org.jdom.transform includes translating jdom XML document interfaces into other XML document interfaces

Org.jdom.xpath contains class III, Jdom class descriptions for XPath operations on XML documents

1, org. Jdom the class in this bag is all the data types you want to use when you parse the XML file.











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



Org. Jdom.input

3, input class, generally used for document creation work




Org. Jdom.output

4, Output class, for document conversion output





Pre-use considerations:

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.

Special parser can be made in the following form

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 to be converted through Jdomsource and Jdomresult classes (see later chapters)

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.

Four, Jdom main use method

1.Ducument class

(1) How the document is operated:

element root = new Element ("greeting");

Document 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 ();

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

Document doc = builder.build (new File ("Jdom_test.xml"));

Saxbuilder builder = new Saxbuilder ();

Document doc = builder.build (URL);

Dombuilder has deprecated the Dombuilder.builder (URL) in the new version, and it will be quicker to use sax.

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

Textxml = Textxml +


Textxml = Textxml + "</note>";

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 here is a layer of element collection below the root node

for (Iterator iter = Ls.iterator (); Iter.hasnext ();) {

Element el = (Element) Iter.next ();

if (El.getname (). Equals ("to")) {

System.out.println (El.gettext ());




catch (IOException ex) {

Ex.printstacktrace ();


catch (Jdomexception ex) {

Ex.printstacktrace ();



(3) The conversion between Dom's document and Jdom's document is simple!

Dombuilder builder = new Dombuilder ();

Org.jdom.Document jdomdocument = Builder.build (DOMDocument);

Domoutputter converter = new Domoutputter ()//work with the JDOM document ...

Org.w3c.dom.Document DOMDocument = Converter.output (jdomdocument);

Work with the DOM document ...

2.XML Document output

Xmloutputter class:

Jdom's output is flexible and supports many IO formats and style output

Document doc = new document (...);

Xmloutputter OUTP = new Xmloutputter ();

Outp.output (Doc, FileOutputStream); Raw output

Outp.settexttrim (TRUE); Compressed output

Outp.output (Doc, Socket.getoutputstream ());

Outp.setindent ("");//Pretty output

Outp.setnewlines (TRUE);

Outp.output (Doc, System.out);

See the latest Jdom API manual for details

3.Element class:

(1) Browse the element tree

Element root = Doc.getrootelement ();//Get root elements element

List Allchildren = Root.getchildren ();//Get a list of all child elements

List Namedchildren = Root.getchildren ("name");//Get a list of child elements of the specified name

Element child = Root.getchild ("name");//Gets the first element of the specified name

Jdom gives us a lot of flexible ways to manage child elements (the List here is Java.util.List)

List Allchildren = Root.getchildren ();

Allchildren.remove (3); Delete a fourth child element

Allchildren.removeall (Root.getchildren ("Jack"));/delete the child element called "Jack"

Root.removechildren ("Jack"); Convenient wording

Allchildren.add (New Element ("Jane"));/join

Root.addcontent (New Element ("Jane")); Convenient wording

Allchildren.add (0, New Element ("a");

(2) Mobile elements:

It's simple in jdom.

element movable = new Element ("movable");

Parent1.addcontent (movable); Place

Parent1.removecontent (movable); Remove

Parent2.addcontent (movable); Add

In the DOM.

Element movable = doc1.createelement ("movable");

Parent1.appendchild (movable); Place

Parent1.removechild (movable); Remove

Parent2.appendchild (movable); Error!

Add: Error correction

The Jdom element constructor (and its other functions) checks to see if the element is legitimate.

And its Add/remove method checks the tree structure, and the check reads as follows:

1. Whether there is a loop 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


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 interpret special characters correctly

Element.settext ("<xml> content");

4.CDATA of data writing, reading out

Element.addcontent (New CDATA ("<xml> content"));

String nodifference = Element.gettext ();

Mixed content

An element may contain a variety of content, such as


<!--Some comment-->

Some text

<tr>some Child element</tr>


Take the child element of the table TR

String text = Table.gettexttrim ();

Element tr = table.getchild ("tr");

You can also use a more simple method

List Mixedco = Table.getcontent ();

Iterator ITR = Mixedco.iterator ();

while (Itr.hasnext ()) {

Object o = I.next ();

if (o instanceof Comment) {...}

This can be written as comment, Element, Text, cdata,processinginstruction, or entityref type.


Now remove the comment, and note that the cursor here 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>

String width = table.getattributevalue ("width");

int border = Table.getattribute ("width"). Getintvalue ();

Table.setattribute ("vspace", "0");/Set attribute

Table.removeattribute ("vspace");/delete one or all attribute

Table.getattributes (). Clear ();

5. Processing instruction (processing instructions) operation

An example of pls


<?cocoon-process type= "XSLT"?>

| |

| |

Target data

Processing target name (target)

String target = Pi.gettarget ();

All data (data) is obtained, and all of it will be returned after target.

String data = Pi.getdata ();

String type = Pi.getvalue ("type"); Get the data for the specified property

List ls = pi.getnames (); Get the names of all the properties

6. Namespace operations


Xmlns:xhtml= "http://www.w3.org/1999/xhtml" >

<xhtml:title>home page</xhtml:title>


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 transform an 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);



Five, use cases:

1. Generate XML Document:

public class writexml{

public void buildXML () throws Exception {

Element Root,student,number,name,age;

root = new Element ("Student-info"); Generate root element: Student-info

Student = new Element ("Student"); Build element: Student (Number,name,age)

Number = new Element ("number");

name = new Element ("name");

Age = New Element (' age ');

Document doc = new document (root); Implanting the root element into document Doc

Number.settext ("001");

Name.settext ("Lnman");

Age.settext ("24");

Student.addcontent (number);

Student.addcontent (name);

Student.addcontent (age);

Root.addcontent (student);

Format format = Format.getcompactformat ();

Format.setencoding ("gb2312"); Set the character of the XML file to gb2312

Format.setindent (""); Set the indent of an XML file to 4 spaces

Xmloutputter xmlout = new Xmloutputter (format),//element after line of one-layer element indent four lattice

Xmlout.output (Doc, New FileOutputStream ("Studentinfo.xml"));


public static void Main (string[] args) throws Exception {

WriteXml w = new WriteXml ();

System.out.println ("Now we build an XML document ...");

W.buildxml ();

System.out.println ("finished!");



The resulting XML document is:

<?xml version= "1.0" encoding= "gb2312"?>








Create XML Document 2:

public class Createxml {

public void Create () {

try {

Document doc = new document ();

ProcessingInstruction pi=new processinginstruction ("Xml-stylesheet", "type=" text/xsl "href=" test.xsl "");

Doc.addcontent (PI);

Namespace ns = Namespace.getnamespace ("http://www.bromon.org");

Namespace ns2 = Namespace.getnamespace ("Other", "http://www.w3c.org");

element root = new Element ("root element", NS);

Root.addnamespacedeclaration (NS2);

Doc.setrootelement (root);

Element el1 = new Element ("element one");

El1.setattribute ("Property", "Property One");

Text text1=new text ("element value");

element em = new Element ("element two"). Addcontent ("second element");

El1.addcontent (Text1);

El1.addcontent (EM);

Element El2 = new Element ("element three"). Addcontent ("third element");

Root.addcontent (EL1);

Root.addcontent (EL2);

Indent four spaces, wrapping automatically, gb2312 encoding

Xmloutputter outputter = new Xmloutputter ("", True, "GB2312");

Outputter.output (Doc, New FileWriter ("Test.xml"));

}catch (Exception e) {

System.out.println (e);



public static void Main (String args[]) {

New Createxml (). Create ();



2, read the XML document example:

Import org.jdom.output.*;

Import org.jdom.input.*;

Import org.jdom.*;

Import java.io.*;

Import java.util.*;

public class readxml{

public static void Main (string[] args) throws Exception {

Saxbuilder builder = new Saxbuilder ();

Document Read_doc = Builder.build ("Studentinfo.xml");

Element stu = Read_doc.getrootelement ();

List List = Stu.getchildren ("student");

for (int i = 0;i < List.size (); i++) {

Element e = (element) list.get (i);

String Str_number = E.getchildtext ("number");

String str_name = E.getchildtext ("name");

String str_age = E.getchildtext ("Age");

System.out.println ("---------STUDENT--------------");

System.out.println ("Number:" + str_number);

System.out.println ("NAME:" + str_name);

System.out.println ("Age:" + str_age);

System.out.println ("------------------------------");

System.out.println ();




3, the DTD verification:

public class Xmlwithdtd {

public void Validate () {

try {

Saxbuilder builder = new Saxbuilder (true);

Builder.setfeature ("Http://xml.org/sax/features/validation";, true);

Document doc = builder.build (new FileReader ("Author.xml"));

System.out.println ("Get it Done");

Xmloutputter outputter = new Xmloutputter ();

Outputter.output (Doc, System.out);

}catch (Exception e) {

System.out.println (e);



public static void Main (String args[]) {

New Xmlwithdtd (). validate ();



It should be noted that this program does not indicate which DTD file to use. The location of the DTD file is specified in XML, and the DTD does not support namespaces, and an XML can reference only one DTD, so the program reads the DTD specified in the XML directly, without specifying the program itself. But in this way, it seems like you can only use an external DTD reference? Expert advice.

4, XML schema validation:

public class Xmlwithschema {

String xml= "Test.xml";

String schema= "Test-schema.xml";

public void Validate () {

try {

Saxbuilder builder = new Saxbuilder (true);

Specify constraint as XML Schema

Builder.setfeature ("Http://apache.org/xml/features/validation/schema";, true);

Import schema file

Builder.setproperty ("Http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation";, schema);

Document doc = builder.build (new FileReader (XML));

System.out.println ("Get it Done");

Xmloutputter outputter = new Xmloutputter ();

Outputter.output (Doc, System.out);

}catch (Exception e) {

System.out.println ("Validation failed:" +e);




The above program indicates the location of the XML schema file to be introduced.

The default output of the system is UTF-8, which may result in garbled characters.

5. XPath Example:

Jdom's API for XPath is in the Org.jdom.xpath package. Under this package, there is an abstract class Xpath.java and implementation class Jaxenxpath.java, using the XPath class's static method Newinstance (String XPath) to get the XPath object, and then call its selectnodes ( Object Context method or selectSingleNode method, which returns a set of nodes (list objects) based on an XPath statement, and returns the first node that meets the criteria based on an XPath statement ( Object type). See jdom-1.0 's sample program:

It analyzes the number of registered servlet and the number of parameters in the Web.xml file and outputs the role name.

Web.xml file:

<?xml version= "1.0" encoding= "Iso-8859-1"?>


<! DOCTYPE Web-app

Public "-//sun Microsystems, INC.//DTD Web application 2.2//en"

"Http://java.sun.com/j2ee/dtds/web-app_2.2.dtd" >








<servlet-name>file </servlet-name>





<description>the initial value for the counter <!--optional--></description>














Processing program:

Import java.io.*;

Import java.util.*;

public class XPathReader {

public static void Main (string[] args) throws IOException, Jdomexception {

if (args.length!= 1) {

System.err.println ("Usage:java xpathreader web.xml");



String filename = args[0];//input web.xml from the command line

PrintStream out = System.out;

Saxbuilder builder = new Saxbuilder ();

Document doc = Builder.build (new File (filename));//Get Document Object

Print servlet Information

XPath Servletpath = xpath.newinstance ("//servlet");//, select a servlet element under any path

List servlets = servletpath.selectnodes (doc);//returns all servlet elements.

Out.println ("This WAR has" + servlets.size () + "registered Servlets:");

Iterator i = Servlets.iterator ();

while (I.hasnext ()) {//Output servlet information

Element servlet = (Element) I.next ();

Out.print ("T" + servlet.getchild ("Servlet-name")

. Gettexttrim () +

"For" + Servlet.getchild ("Servlet-class")

. Gettexttrim ());

List initparams = Servlet.getchildren ("Init-param");

Out.println ("(It has" + initparams.size () + "init params)");


Print Security Role Information

XPath Rolepath = Xpath.newinstance ("//security-role/role-name/text ()");

List rolenames = rolepath.selectnodes (doc);//Get all the role names

if (rolenames.size () = = 0) {

Out.println ("This WAR contains no roles");

} else {

Out.println ("This WAR contains" + rolenames.size () + "roles:");

i = Rolenames.iterator ();

while (I.hasnext ()) {//Output role name

Out.println ("T" + (Text) I.next ()). Gettexttrim ());





Output results:

C:\java>java XPathReader Web.xml

This WAR has 2 registered Servlets:

Snoop for Snoopservlet (it has 0 init params)

File for Viewfile (it has 1 init params)

This WAR contains 3 roles:




6, data input to use the XML document to pass Org.jdom.input package, in turn, the need for org.jdom.output. As mentioned above, it is possible to use the API documentation to see it.

Our example reads the XML file Examplea.xml, adds a processing instruction, modifies the price and author of the first book, adds an attribute, and then writes to the file Exampleb.xml:


<?xml version= "1.0" encoding= "GBK"?>



Introduction to <name>java Programming </name>

<author> John </author>





The application of <name>xml in Java </name>

<author> Dick </author>






Import org.jdom.*;

Import org.jdom.output.*;

Import org.jdom.input.*;

Import java.io.*;

public class testjdom{

public static void Main (String args[]) throws exception{

Saxbuilder sb = new Saxbuilder ();

Constructs a document from a file, because the encoding is already specified in the XML file, so there is no need to

Document doc = sb.build (new FileInputStream ("Examplea.xml"));

ProcessingInstruction pi = new processinginstruction//add a processing instruction

("Xml-stylesheet", "href=\" booklist.html.xsl\ "type=\" "text/xsl\");

Doc.addcontent (PI);

Element root = Doc.getrootelement (); Get the root element

Java.util.List books = Root.getchildren (); Gets the collection of all child elements of the root element

Element book = (element) books.get (0); Get the first book element

Add a property to the first book

Attribute A = new attribute ("Hot", "true");

Book.setattribute (a);

Element author = book.getchild ("author"); Gets the specified Word element

Author.settext ("Harry"); Change the author to Harry

or text t = new text ("Harry"); Book.addcontent (t);

Element Price = Book.getchild (' price '); Gets the specified Word element

Change the price, the more depressing thing is that we have to transform the data type ourselves, which is the advantage of JAXB

Author.settext (float.tostring (50.0f));

String indent = "";

Boolean newlines = true;

Xmloutputter OUTP = new Xmloutputter (indent,newlines, "GBK");

Outp.output (Doc, New FileOutputStream ("Exampleb.xml"));



Execution Results Exampleb.xml:

<?xml version= "1.0" encoding= "GBK"?>


<book hot= "true" >

Introduction to <name>java Programming </name>






The application of <name>xml in Java </name>

<author> Dick </author>





<?xml-stylesheet href= "bookList.html.xsl" type= "text/xsl"?>

By default, methods such as the GetText () of the Jdom element class do not filter whitespace characters, if you need to filter, with Settexttrim ().

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.