Java dom4j Several methods used to parse XML _java

Source: Internet
Author: User

1. To read and parse an XML document:

Copy Code code as follows:

Saxreader reader = new Saxreader ();
Document document = Reader.read (new File (FileName));

Reader's Read method is overloaded and can be read from InputStream, File, URL, and many different sources. The resulting Document object takes a table of the entire XML.
The character encoding that is read is converted according to the encoding defined by the header of the XML file. If you encounter garbled problems, pay attention to the code names everywhere to keep the same.

2. Get root node

Element root=document.getrootelement ();
The root element is the roots node of the XML document. All XML parsing starts with the root element.

3. Traversing an XML tree
DOM4J provides at least 3 ways to traverse a node:
 

Copy Code code as follows:

Enumerate all child nodes
for (Iterator i = Root.elementiterator (); I.hasnext ();) {
element element = (Element) I.next ();
Do something
}
Enumeration of nodes named Foo
for (Iterator i = Root.elementiterator (foo); I.hasnext ();) {
element foo = (element) I.next ();
Do something
}
Enumeration properties
for (Iterator i = Root.attributeiterator (); I.hasnext ();) {
attribute attribute = (attribute) i.next ();
Do something
}

Copy Code code as follows:

List<element> elementlist=root.elements (); Gets all the child nodes under the root element.
String Elementname=element.getname (); Get the name of the element node
String Elementvalue=element.gettext (); Get the text node value of the element node
Attribute Attribute=element.attribute (); To get the attributes of an element node
String attrvalue=element.attributevalue ("AttrValue"); Get property value

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.