How to Use JDOM to read XML documents

Source: Internet
Author: User
Tags cdata processing instruction xml file example xsl
Introduction: JDOM is a new API function that reads, writes, and operates XML in Java. Jason Hunter and Brett McLaughlin publicly released Version 1.0. These API functions are optimized to the maximum extent on the premise of intuition, simplicity, and efficiency. The following section describes how to use JDOM to read and write an existing XML document.
Keywords: Java, JDOM, XML
Java + xml = JDOM!
This is the goal of the JDOM designer. If you have used annoying sax or Dom to process XML, you will know why JDOM is required. at the javaone Conference in 2002, Jason Hunter, the main founder of JDOM, gave a wonderful speech about JDOM Technology, which is JDOM makes XML easy.
We know that Dom is the official W3C standard for expressing XML documents in a way unrelated to the platform and language. Dom and sax APIs can be used to parse and process XML documents. Here we introduce JDOM, a pure Java API Based on Tree operations. It should be said that it provides a set of solutions for parsing, creating, coming out, and implementing XML.
II. Environment Configuration
Use jdk-1_5_0_06 as a development and testing platform on my windows xp platform.
3. obtain and install JDOM
Currently, JDOM is not included in Sun's JDK (I think JDOM will inevitably become part of Sun's JDK in the near future). We must manually download and set the JDOM environment.
In the http://www.jdom.org, you can download the latest version of JDOM. Here the download is jdom-1.0. The jdom jar file is the JDOM file under the build directory. jar, copy the above file to the JRE/lib/EXT directory under the jdk-1_5_0_06 directory, and use eclipse users can manually add to the user liberary

JDOM model:
Each element has four key segments:

1. Name
2. Element attributes
3. Element range namespace
4. Element Content

The general process of using JDOM to process existing XML documents is as follows:
1. Construct an org. JDOM. Input. saxbuilder object using a simple non-variable element constructor. Saxbuilder uses the SAX Parser to construct a document from a file. Saxbuilder listens to the sax event and creates a document from the memory. This method is very fast (basically as fast as SAX), and the speed of JDOM has the potential to be improved with an extended constructor. This constructor checks the XML data source, but parses it only when requested. For example, the attributes of a document do not need to be parsed when they are not accessed. The constructor is still developing and can be used to create JDOM documents through SQL queries, LDAP queries, and other data formats. Therefore, once you enter the memory, the document has nothing to do with the tool for building it.
2. Use the build () method of the builder to create a document object from Reader, inputstream, URL, file, or a string containing the System ID.
3. If reading a document encounters a problem, an ioexception is thrown. If a document is created, a jdomexception is thrown.
4. Otherwise, use the document class, element class, and other JDOM class methods to establish navigation in the document.

navigation JDOM tree
each element object contains a column of child elements: Comment, processinginstruction, text, and other element objects. In addition, attributes and other namespaces are listed separately.
after the document is analyzed and the document object is created, you may need to search for the Programs that interest you. In JDOM, most navigation is performed through the element class method. Complete sub-elements of each element (including all the content of sub-elements, including instructions, processing instructions, text nodes, and elements) must be searched in depth, the getcontent () method must be applied to the child elements of the current element. recursion is usually used.) The getcontent () method returns Java. util. list. The getchildren () method returns only the child elements of each element in Java. util. List.
the JDOM processing method is similar to Dom, but it is mainly implemented using sax, so you don't have to worry about processing speed and memory. In addition, there are almost no interfaces in JDOM, and all the classes are real classes without class factory classes. The most important package is Org. JDOM mainly has the following classes:
document (document node)
each document object includes the following three attributes:
1. root element
2. doctype object indicating document type declaration
3. list containing root elements and any processing instructions and instructions,
attribute (attribute node)
Public element setattributes (list attributes) throws illegaladdexception
public list getattributes ()
setattribute ()
getattribute ()
getattributevalue ()
attribute. getname ()
attribute. getvalue ()

CDATA (CDATA segment node)
Comment)
XML file Description: <! -- Wire configuration -->
Doctype (Document Type node)
Element)
Set and retrieve element names
Public element setname (string name) throws illegalnameexception
Public String getname ()

Public String get (int I) // I> = 0

Content)
Public element setcontent (list) throws illegaladdexception;
Public list getcontent ();
Addcontent ();
Removecontent ();

Entityref (instance node)
Namespace (namespace node)
Processinginstruction (processing command node)

Text (text node)
Gettext ();
Settext (string S );
 
Example. xml file

<? XML version = "1.0" encoding = "GBK"?>
<Booklist>
<Book>
<Name> JAVA Programming basics </Name>
<Author> Zhang San </author>
<Publishdate> 2002-6-6 </publishdate>
<Price> 35.0 </price>
</Book>
<Book>
<Name> application of XML in Java </Name>
<Author> Li Si </author>
<Publishdate> 2002-9-16 </publishdate>
<Price> 92.0 </price>
</Book>
</Booklist>

Cute. xml file


// rootelement
// ----> attribute
JAVA getting started with programming // This Is My text content
cute
2002-6-6
50.0

application of XML in Java
Li Si
2002-9-16
92.0

The XML document used for data input must use the org. JDOM. Input package, which in turn requires org. JDOM. output. As mentioned above, you can use it by reading the API documentation.
In our example, we read the XML file example. XML, add a processing command, modify the price and author of the first book, add an attribute, and write the file cute. xml

Cute. Java:

Package JDOM;

Import org. JDOM .*;
Import org. JDOM. Input .*;
Import org. JDOM. Output .*;
Import java. Io .*;
Import java. util .*;

Public class cute {

Public static void main (string ARGs []) {
try {
/*
* construct a saxbuilder object using the non-variable element constructor, construct a document from a file using the SAX Parser,
* saxbuilder listens on a sax event and creates a document from the memory
*/
saxbuilder sb = new saxbuilder ();
// create a document
document DOC = sb. build (New fileinputstream ("example. XML ");
// Add a Processing Instruction
processinginstruction Pi = new processinginstruction (
" XML-stylesheet ",
"href = \" booklist.html. XSL \ "type = \" text/XSL \ "");
// Add this processing instruction to the document.
Doc. addcontent (PI);
// obtain the root element of this document
element root = Doc. getrootelement ();
JAVA. util. list ls = root. getchildren ();
// obtain all the child elements of the root element (the child element does not contain the child element), but completely ignores the iterator I = ls. iterator ();

While (I. hasnext ()){
Object o = I. Next ();
If (O instanceof text)/* use instanceof to obtain the required content */
{Text t = (text) O;
System. Out. println ("text:" + T. gettext ());}
Else if (O instanceof attribute)
System. Out. println ("attribute:" + O );
Else if (O instanceof element)
System. Out. println ("element:" + (element) O). getname ());
}

// Obtain the child element of the first child element, but ignore its content completely.
Element book = (element) ls. Get (0 );
// Add an attribute to this child element,
Attribute ATTR = new attribute ("hot", "true ");
Book. setattribute (ATTR );
// Obtain the child element (specified) and its value of this element.
Element EL2 = book. getchild ("author ");
// Output the value of this element
System. Out. println (el2.getname ());
// Rename the value of this element
El2.settext ("cute ");
// Obtain the child element of this element (specified)
Element EL3 = book. getchild ("price ");
// Change the value
El3.settext (float. tostring (50366f ));
String indent = "";
Boolean newlines = true;
Xmloutputter xml = new xmloutputter (indent, newlines, "gb2312 ");
XML. Output (Doc, new fileoutputstream ("E: \ cute. xml "));
} Catch (exception e ){
System. Out. println (E. getmessage ());

}

}
}

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.