Java dom4j parses XML in several ways
- 2020-04-01 02:39:12
- OfStack
1. Read and parse XML documents:
SAXReader reader = new SAXReader();
Document document = reader.read(new File(fileName));
The reader's read method is overloaded and can be read from various sources such as InputStream, File, Url, etc. The resulting Document object takes the entire XML with it.
The character encodings read are converted according to the encodings defined in the XML file header. If you encounter a problem with garbled code, be careful to keep the code name consistent.
2. Get the Root node
Element root = document. GetRootElement ();
The root element is the root node of an XML document. All XML analysis starts with the Root element.
3. Traverse XML tree
DOM4J provides at least three ways to traverse nodes:
//Enumerate all child nodes
for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
Element element = (Element) i.next();
// do something
}
//Enumerate the node named foo
for ( Iterator i = root.elementIterator(foo); i.hasNext();) {
Element foo = (Element) i.next();
// do something
}
//Enumerated attribute
for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
Attribute attribute = (Attribute) i.next();
// do something
}
List<Element> elementList=root.elements(); Gets all child nodes under the root element.
String elementName=element.getName(); To obtain element Node name
String elementValue=element.getText(); To obtain element The text node value of the node
Attribute attribute=element.attribute(); To obtain element Properties of nodes
String attrValue=element.attributeValue("attrValue"); Get the attribute value