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