JAVA解析xml得到节点的值

2025-04-03 14:40:50
推荐回答(2个)
回答1:

import java.io.File;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ParseXml {
public static void main(String[] args) throws DocumentException {
SAXReader reader = new SAXReader();
Document doc = reader.read(new File("d:/test.xml"));
Element root = doc.getRootElement();
Element record = root.element("Record");
Iterator it = record.elementIterator("Field");
while (it.hasNext()) {
Element element = it.next();
Element name = element.element("Name");
System.out.println(name.getText());
Element value = element.element("Value");
ParseXml.parseValue(value);
}
}

public static void parseValue(Element value) {
Iterator it = value.elementIterator();
if (it.hasNext()) {
while (it.hasNext()) {
Element element = it.next();
Element innerField = element.element("Field");
Element innerName = innerField.element("Name");
System.out.println(innerName.getText());
Element innerValue = innerField.element("Value");
parseValue(innerValue);
}
} else {
System.out.println(value.getText());
}
}
}

回答2:

org.w3c.dom.Node

有方法
String
getNodeName()
The name of this node, depending on its type; see the table above.

short
getNodeType()
A code representing the type of the underlying object, as defined above.

String
getNodeValue()
The value of this node, depending on its type; see the table above.