The Jdom of Java and XML

Source: Internet
Author: User
Tags add format object empty interface string version window
Dom|xml

In JDOM, an XML element is an instance of an element, and an XML attribute is an instance of an attribute, which is an instance of the document itself.
Because JDOM objects are direct instances of classes like Document, Element, and Attribute, creating a new JDOM object is as easy as using the new operator in the Java language. The use of JDOM is straightforward.
JDOM uses the standard Java encoding pattern. Whenever possible, it uses the Java new operator instead of using complex factory patterns, making object manipulation even easier for novice users.

This paper introduces the application of Jdom in two steps: XML creation and XML parsing
First, XML document creation
We use Jdom to generate an XML document from zero. 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 with MyInfo as the root element
Element rootelement = new Element ("MyInfo");//All XML elements are instances of the element. The root element is no exception:)
Document myDocument = new document (rootelement);//Create a Document object as an argument to the root element. A document has only one root, that is, the root element.
2. Add attributes to the root element
Attributes Rootattri = new Attribute ("comment", "introduce Myself");//Create a property named Commnet with a value of introduce myself.
Rootelement.setattribute (Rootattri);//Adds the property you just created to the root element.
These two lines of code you can also compose a line to write, like this:
Rootelement.setattribute (New Attribute ("comment", "introduce Myself"));
Or
Rootelement.setattribute ("comment", "introduce Myself");
3. Adding elements and child elements
Jdom lining elements are added to the parent element as content (contents), so the content is similar to the kingwong between <name></name> in the above sample document. It's a little wordy, right?
Element nameelement = new Element ("name");//Create name Element
Nameelement.addcontent ("Kingwong");//Add Kingwong as content to the name element
Rootelement.addcontent (nameelement);//Add the name element as content to the root element

These three lines can also be combined as a sentence, like this:
Rootelement.addcontent (content) (New Element ("name"). Addcontent ("Kingwong"));//Because addcontent (content child) method returns a parent interface, and the element class inherits the content class and implements the parent interface, so we shape it into content.

We use the same method to add a child element with attributes <sex value= "male"/>
Rootelement.addcontent (New Element ("Sex"). setattribute ("value", "male");/note there is no need to transform because AddAttribute (String name, String value) is the return value of an Element.

Similarly, we add <contract/> elements to the root element, just as in usage, but slightly more complex:
Rootelement.addcontent (content) (new element ("contact"). Addcontent (content) (new element ("Telephone"). Addcontent ("87654321")));
If you're not used to this shorthand, you can do it all at once, just as it was at the beginning of this section. In fact, if the level is more, write step-by-step form more clearly, it is not easy to make mistakes.
4. Delete child elements
This operation is relatively simple:
Rootelement.removechild ("Sex");/The method returns a Boolean value

So far, we've learned the Jdom document generation operation. A sample document was created, but how do we know right from wrong? So you need to look at the output. We output the JDOM-generated document to the console, using the JDOM Xmloutputter class.
5. Convert JDOM to XML text
Xmloutputter xmlout = new Xmloutputter ("", true);
try {
Xmlout.output (mydocument,system.out);
catch (IOException e) {
E.printstacktrace ();
}
Xmloutputter has several formatting options. Here we have specified that you want the child element to indent two spaces from the parent element, and that you want a blank line between the elements.
New Xmloutputter (java.lang.String indent, Boolean newlines) This method is not recommended in the latest version. Jdom has a specialized class for defining formatted output: Org.jdom.output.Format, if you don't have special requirements, sometimes it's OK to use several static methods (which should be called predefined formats) like Getprettyformat (). Let's change the output format slightly, like this:
Xmloutputter xmlout = new Xmloutputter (Format.getprettyformat ());
6. Convert Jdom documents to other forms
Xmloutputter can also be exported to Writer or OutputStream. In order to output jdom documents 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 a string to be processed later in the program:
Strng outstring = xmlout.outputstring (myDocument);

Of course, you do not have to output all the entire document at the time of the output, you can select the element to output:
Xmlout.output (Rootelement.getchild ("name"), System.out);
In a word, jdom is very flexible and convenient! If you want to further study jdom, please go to the official website to take a look at: http://www.jdom.org
This section sample source code:
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 of 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. Parsing XML documents
JDOM not only makes it easy to build an XML document, it's another use for it to read and manipulate existing XML data.
The Jdom parser is in the org.jdom.input.* package, where the Dombuilder function is to parse the document of the DOM model into the document of the JDOM model The function of Saxbuilder is to parse an XML tree that conforms to the Jdom model from a file or stream. Since we often read data from a file, we should use the latter as the parsing tool.
Parsing an XML document can be viewed as a few of the following steps:
1. Instantiate an appropriate parser object
In this example we use Saxbuilder:
Saxbuilder sb = new Saxbuilder ();
2. Construct a Document object with a file that contains XML data as a parameter mydocument
Document myDocument = Sb.build (/some/directory/myfile.xml);
3. Get to root element
Element rootelement = Mydocument.getrootelement ();

Once you have acquired the root element, you can easily manipulate the child elements below it, and here is a brief description of some common methods of the element object:
Getchild ("ChildName") returns the child node of the specified name, and if there are multiple child nodes of the same name at the same level, only the first one is returned, if no null value is returned.
GetChildren ("ChildName") returns the list of child nodes of the specified name. This allows you to traverse all the same child nodes of the same level.
Getattributevalue ("name") returns the value of the specified property name. Returns null if the property is not available, with the property but the value is empty, and an empty string is returned.
Getchildtext ("ChildName") returns the content text value of the specified child node.
GetText () returns the content text value of the element.

There are other methods that are not listed, and you can check jdom's online documentation at any time if you want: http://www.jdom.org/docs/apidocs/index.html. Of course you can add and remove element operations where you need to, remember the above method of creating XML? Oh ~ ~ ~ ~

Learn new things or learn from an instance of the quickest, the following simple example, the above XML sample code to learn jdom XML parsing. In this example, we read some attributes and content in the sample XML file, and finally we insert a new element in the contact element <email value= "wanghua@cyberobject.com"/>. Although we have implemented the basic operation of XML, attentive friends may
There is a question: If the hierarchy of XML documents is slightly more complex, it would be very painful if you nested up to dozens of hundreds of layers (joking) to access the child elements from the root element level through Getchild ("ChildName"). Yes, it does, but we have another powerful tool XPath, why not? This is something! First sell a check (hand knock tired, next bar, hehe).

/*
* Created on 2004-8-21
*
* TODO to change the template of 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 of 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 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 ();
}
}
}



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.