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