Recently, we often have to deal with documents or strings in XML format. It is very convenient to use JDOM. This allows you to quickly develop XML applications.
In JDOM, the XML element is the element instance, the XML Attribute is the attribute instance, and the XML document itself is the document instance.
Because JDOM objects are direct instances of classes such as document, element, and attribute, creating a new JDOM object is as easy as using the new operator in Java. The use of JDOM is straightforward.
JDOM uses the standard Java encoding mode. As long as possible, it uses the Java new operator instead of the complicated factory mode, making object operations very convenient for beginners.
This article introduces JDOM applications in two steps: XML creation and XML parsing.
I. Create an XML document
We use JDOM to generate an XML document from scratch. The final result (sample document) looks like this:
<? XML version = "1.0" encoding = "UTF-8"?>
<Myinfo comment = "introduce myself">
<Name> kingwong </Name>
<Sex value = "male"/>
<Contact>
<Telephone> 87654321 </telephone>
</Contact>
</Myinfo>
1. Create a document using myinfo as the root element
Element rootelement = new element ("myinfo"); // all XML elements are element instances. The root element is no exception either :)
Document mydocument = new document (rootelement); // create a document object with the root element as the parameter. A document has only one root, that is, the root element.
2. Add attributes to the root element
Attribute rootattri = new attribute ("comment", "introduce myself"); // create an attribute named commnet with the value of introduce myself.
Rootelement. setattribute (rootattri); // Add the newly created attribute to the root element.
You can combine the two lines of code to write them, as shown in the following code:
Rootelement. setattribute (new attribute ("comment", "introduce myself "));
Or
Rootelement. setattribute ("comment", "introduce myself ");
3. Add elements and child elements
The child element in JDOM is added to the parent element as content. The so-called content is something similar to the <Name> </Name> in the sample document above, that is, kingwong. A :)
Element nameelement = new element ("name"); // create a name Element
Nameelement. addcontent ("kingwong"); // Add kingwong as content to the name Element
Rootelement. addcontent (nameelement); // Add the name element as the content to the root element.
You can also combine these three lines as follows:
Rootelement. addcontent (content) (new element ("name "). addcontent ("kingwong"); // because the addcontent (content child) method returns a parent interface, the element class inherits the content class and implements the parent interface at the same time, so we shape it into content.
We use the same method to add sub-elements with attributes <sex value = "male"/>
Rootelement. addcontent (new element ("sex "). setattribute ("value", "male"); // note that no transformation is required here, because the returned value of addattribute (string name, string value) is an element.
Similarly, we add the <contract/> element to the root element. The usage is the same, but it is a little complicated:
Rootelement. addcontent (content) (new element ("Contact "). addcontent (content) (new element ("telephone "). addcontent ("87654321 ")))));
If you are not familiar with this short form, you can do it step by step, just like at the beginning of this section. In fact, if there are many layers, the step-by-step format is clearer and it is not prone to errors.
4. delete child elements
This operation is relatively simple:
Rootelement. removechild ("sex"); // This method returns a Boolean value.
So far, we have learned how to generate JDOM documents. We have created a sample document above, but how do we know it? Therefore, let's take a look at the output. We output the documents generated by JDOM to the console and use the xmloutputter class of JDOM.
5. Convert JDOM into XML text
Xmloutputter xmlout = new xmloutputter ("", true );
Try {
Xmlout. Output (mydocument, system. Out );
} Catch (ioexception e ){
E. printstacktrace ();
}
Xmloutputter has several format options. Here we have specified that we want the child element to indent two spaces from the parent element, and we want the child element to have blank lines between them.
New xmloutputter (Java. Lang. String indent, Boolean newlines) is not recommended in the latest version. JDOM has a special class for defining formatted output: Org. JDOM. output. format. If you do not have special requirements, you can use several static methods (such as pre-defined formats) such as getprettyformat. Let's change the output format a bit, just like this:
Xmloutputter xmlout = new xmloutputter (format. getprettyformat ());
6. Convert the JDOM document into other forms
Xmloutputter can also be output to writer or outputstream. To output a JDOM document to a text file, we can do this:
Filewriter writer = new filewriter ("/Some/directory/myfile. xml ");
Outputter. Output (mydocument, writer );
Writer. Close ();
Xmloutputter can also be output to strings for subsequent processing by the Program:
Strng outstring = xmlout. outputstring (mydocument );
Of course, you do not have to output all the documents during output. You can select the elements for output:
Xmlout. Output (rootelement. getchild ("name"), system. Out );
In a word, JDOM is very flexible and convenient! If you want to study JDOM further, go to the official website to see: http://www.jdom.org
Sample source code in this section:
Package com. cyberobject. study;
Import java. Io. ioexception;
Import org. JDOM. Attribute;
Import org. JDOM. content;
Import org. JDOM. Document;
Import org. JDOM. element;
Import org. JDOM. Output. format;
Import org. JDOM. Output. xmloutputter;
/**
* @ Author kingwong
*
* Todo to change the template for this generated type comment go
* Window-preferences-Java-code style-code templates
*/
Public class testjdom {
Public static void main (string [] ARGs)
{
Element rootelement = new element ("myinfo ");
Document mydocument = new document (rootelement );
// Attribute rootattri = new attribute ("comment", "introduce myself ");
// Rootelement. setattribute (rootattri );
Rootelement. setattribute ("comment", "introduce myself ");
// Rootelement. setattribute (new attribute ("comment", "introduce myself "));
// Element sexelement = new element ("sex ");
// Rootelement. addcontent (sexelement );
// Element nameelement = new element ("name ");
// Nameelement. addcontent ("kingwong ");
// Rootelement. addcontent (nameelement );
Rootelement. addcontent (content) (new element ("name"). addcontent ("kingwong ")));
Rootelement. addcontent (new element ("sex"). setattribute ("value", "male "));
Rootelement. addcontent (content) (new element ("contract "). addcontent (content) (new element ("telephone "). addcontent ("87654321 ")))));
Rootelement. removechild ("sex ");
Xmloutputter xmlout = new xmloutputter (format. getprettyformat ());
Try {
Xmlout. Output (mydocument, system. Out );
// Xmlout. Output (rootelement. getchild ("name"), system. Out );
// String outstring = xmlout. outputstring (mydocument );
} Catch (ioexception e ){
E. printstacktrace ();
}
}
}
Ii. XML document Parsing
JDOM not only facilitates the creation of XML documents, but also facilitates the reading and operation of existing XML data.
The JDOM parser is in org. JDOM. input. * In this package, the dombuilder function is to parse the document of the DOM model into the document of the JDOM model. The saxbuilder function is to parse the XML tree conforming to the JDOM model from a file or stream. Since we often need to read data from a file, we should use the latter as a parsing tool.
To parse an XML document, follow these steps:
1. instantiate a suitable parser object
In this example, we use saxbuilder:
Saxbuilder sb = new saxbuilder ();
2. Construct a Document Object mydocument with the file containing XML data as the parameter
Document mydocument = sb. Build (/Some/directory/myfile. XML );
3. Get the root element
Element rootelement = mydocument. getrootelement ();
Once you get the root element, you can easily operate the child elements below it. The following describes some common methods for element objects:
Getchild ("childname") returns the child node with the specified name. If there are multiple child nodes with the same name at the same level, only the first child node is returned. If no null value is returned.
Getchildren ("childname") returns the list set of child nodes with the specified name. In this way, you can traverse all subnodes with the same name at the same level.
Getattributevalue ("name") returns the value of the specified attribute name. If this attribute is not available, null is returned. If this attribute is available but the value is null, an empty string is returned.
Getchildtext ("childname") returns the content text value of the child node.
Gettext () returns the content text value of this element.
There are other methods not listed. If necessary, you can refer to the JDOM online documentation at any time: http://www.jdom.org/docs/apidocs/index.html. Of course, you can add or delete elements as needed. Do you still remember the above method for creating XML? Haha ~~~
Learning new things is still the fastest way to learn from instances. The following is a simple example to learn jdom xml parsing using the above XML sample code. In this example, some attributes and content in the sample XML file are read, and a new element <email value = "wanghua@cyberobject.com"/> is inserted into the contact element. Although we have implemented basic XML operations, careful friends may
Doubt: if the XML document hierarchy is a little more complex, if it is nested with dozens or hundreds of layers (joke ), if you access the child element through getchild ("childname") at the root element level, it will be very painful! Yes, it does. But we have another powerful tool, XPath. Why not? This is a post! Sell a token first (if you're tired, next time, huh, huh ).
/*
* Created on 2004-8-21
*
* Todo to change the template for this generated file go
* Window-preferences-Java-code style-code templates
*/
Package com. cyberobject. study;
Import org. JDOM. Document;
Import org. JDOM. element;
Import org. JDOM. Input. saxbuilder;
Import org. JDOM. Output. format;
Import org. JDOM. Output. xmloutputter;
/**
* @ Author kingwong
*
* Todo to change the template for this generated type comment go
* Window-preferences-Java-code style-code templates
*/
Public class testjdom2 {
Public static void main (string [] ARGs ){
Saxbuilder sb = new saxbuilder ();
Try
{
Document Doc = sb. Build ("myfile. xml ");
Element root = Doc. getrootelement ();
String str1 = root. getattributevalue ("comment ");
System. Out. println ("root element's comment attribute is:" + str1 );
String str2 = root. getchild ("sex"). getattributevalue ("value ");
System. Out. println ("Sex element's value attribute is:" + str2 );
String str3 = root. getchildtext ("name ");
System. Out. println ("name element's content is:" + str3 );
String str4 = root. getchild ("Contact"). getchildtext ("telephone ");
System. Out. println ("Contact Element's telephone subelement content is:" + str4 + "/N ");
Element inputelement = root. getchild ("Contact ");
Inputelement. addcontent (new element ("email"). setattribute ("value", "wanghua@cyberobject.com "));
Xmloutputter xmlout = new xmloutputter (format. getprettyformat ());
String outstr = xmlout. outputstring (Root );
System. Out. println (outstr );
}
Catch (exception E)
{
E. printstacktrace ();
}
}
}
This article from: http://www.360doc.com/showWeb/0/0/165796.aspx