[Backup] XML parsing tool in java-Introduction to dom4j

Source: Internet
Author: User

To use dom4j to read and write XML documents, you need to first download the dom4j package, dom4j official website in http://www.dom4j.org/

Currently the latest dom4j package: http://nchc.dl.sourceforge.net/sourceforge/dom4j/dom4j-1.6.1.zip

There are two packages after the UNDO, only the XML document to operate the dom4j-1.6.1.jar to add the project can be, if you need to use XPath also need to add the package jaxen-1.1-beta-7.jar.

Perform the following operations:

1. Document Object-related

1. Read the XML file and obtain the document object.
Saxreader reader = new saxreader ();
Document document = reader. Read (new file ("input. xml "));

2. parse the text in XML format to obtain the document object.
String text = "<members> </members> ";
Document document = incluenthelper. parseText (text );
3. Create a document Object.
Document document = incluenthelper. createDocument ();
Element root = document. addElement ("members"); // create a root node

Ii. node Problems

1. Get the root node of the document.
Element rootElm = document. getRootElement ();
2. Obtain a single subnode of a node.
Element memberElm = root. element ("member"); // "member" is the node name.
3. Get the node text
String text = memberElm. getText ();
You can also use:
String text = root. elementText ("name"); this is the text that retrieves the name byte under the root node.

4. retrieve all the byte points under a node named "member" and traverse them.
List nodes = rootElm. elements ("member ");

For (Iterator it = nodes. iterator (); it. hasNext ();){
Element elm = (element) it. Next ();
// Do something
}
5. traverse all subnodes under a node.
For (iterator it = root. elementiterator (); it. hasnext ();){
Element element = (element) it. Next ();
// Do something
}
6. Add a subnode under a node.
Element ageelm = newmemberelm. addelement ("Age ");
7. Set the node text.
Ageelm. settext ("29 ");
8. delete a node.
Parentelm. Remove (childelm); // childelm is the node to be deleted, and parentelm is the parent node.

Iii. property-related

1. Obtain an attribute under a node
Element root = document. getRootElement ();
Attribute attribute = root. Attribute ("size"); // attribute name
2. Get the attribute text
String text = attribute. getText ();
You can also use:
String text2 = root. element ("name"). attributeValue ("firstname"); this is the value of the firstname attribute of the name byte point under the root node.

3. traverse all attributes of a node
Element root = document. getRootElement ();
For (Iterator it = root. attributeIterator (); it. hasNext ();){
Attribute attribute Attribute = (Attribute) it. next ();
String text = attribute. getText ();
System. out. println (text );
}
4. Set attributes and text of a node.
NewMemberElm. addattrielm ("name", "sitinspring ");
5. Set the attribute text
Attribute attribute = root. Attribute ("name ");
Attribute. setText ("sitinspring ");
6. delete an attribute
Attribute attribute = root. Attribute ("size"); // attribute name
Root. remove (attribute );

4. Write documents into XML files

1. The document is in full English and is written directly without encoding.
XMLWriter writer = new XMLWriter (new FileWriter ("output. xml "));
Writer. write (document );
Writer. close ();
2. The document contains Chinese characters and sets the encoding format for writing.
OutputFormat format = OutputFormat. createPrettyPrint ();
Format. setEncoding ("GBK"); // specify the XML Encoding
XMLWriter writer = new XMLWriter (new FileWriter ("output. xml"), format );

Writer. Write (document );
Writer. Close ();

5. Conversion of strings and XML

1. convert a string to XML
String text = "<members> <member> sitinspring </member> </members> ";
Document document = incluenthelper. parsetext (text );
2. Convert the XML of the document or node into a string.
Saxreader reader = new saxreader ();
Document document = reader. Read (new file ("input. xml "));
Element root = document. getRootElement ();
String docXmlText = document. asXML ();
String rootXmlText = root. asXML ();
Element memberElm = root. element ("member ");
String memberXmlText = memberElm. asXML ();

6. Use XPath to quickly find a node

Example of an XML document read
<? Xml version = "1.0" encoding = "UTF-8"?>
<ProjectDescription>
<Name> MemberManagement </name>
<Comment> </comment>
<Projects>
<Project> PRJ1 </project>
<Project> PRJ2 </project>
<Project> PRJ3 </project>
<Project> PRJ4 </project>
</Projects>
<BuildSpec>
<BuildCommand>
<Name> org. eclipse. jdt. core. javabuilder </name>
<Arguments>
</Arguments>
</BuildCommand>
</BuildSpec>
<Natures>
<Nature> org. eclipse. jdt. core. javanature </nature>
</Natures>
</ProjectDescription>

Use XPath to quickly find the node project.
Public static void main (String [] args ){
SAXReader reader = new SAXReader ();

Try {
Document doc = reader. read (new File ("sample. xml "));
List projects = doc. selectNodes ("/projectDescription/projects/project ");
Iterator it = projects. iterator ();

While (it. hasNext ()){
Element elm = (Element) it. next ();
System. out. println (elm. getText ());
}

}
Catch (Exception ex ){
Ex. 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.