Several methods used by java dom4j to parse xml

Source: Internet
Author: User

1. Read and parse the XML document:

SAXReader reader = new SAXReader ();
Document document = reader. read (new File (fileName ));

Reader's read method is overloaded and can be read from multiple sources, such as InputStream, File, and Url. The resulting Document object contains the entire XML table.
The read character encoding is based on the encoding defined by the XML file header. In case of garbled characters, make sure that the names of all codes are consistent.

2. Get the Root node

Element root = document. getRootElement ();
The root element is the root node of the xml document. All XML analysis starts with the Root element.

3. traverse the XML tree
DOM4J provides at least three methods to traverse nodes:
1) Iterator)
// Enumerate all subnodes
For (Iterator I = root. elementIterator (); I. hasNext ();){
Element element = (Element) I. next ();
// Do something
}
// Enumerate nodes named foo
For (Iterator I = root. elementIterator (foo); I. hasNext ();){
Element foo = (Element) I. next ();
// Do something
}
// Enumeration attribute
For (Iterator I = root. attributeIterator (); I. hasNext ();){
Attribute attribute Attribute = (Attribute) I. next ();
// Do something
}

List <Element> elementList = root. elements (); obtain all subnodes under the root Element.
String elementName = element. getName (); get the name of the element Node
String elementValue = element. getText (); obtain the text node value of the element node.
Attribute attribute = element. Attribute (); get the attribute of the element Node
String attrValue = element. attributeValue ("attrValue"); get the attribute value

 

Transfer http://www.360doc.com/content/10/1215/14/654841_78361905.shtml

Related Article

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.