2种方式解析xml文件
1 递归的方式
public static void readNode(Element root, String prefix) {
if (root == null)
return;
// 获取节点的属性
List attrs = root.attributes();
if (attrs != null && attrs.size() > 0) {
System.err.print(prefix);
for (Attribute attr : attrs) {
System.err.print(attr.getValue() + ” “);
}
System.err.println();
}
// 获取他的子节点
List childNodes = root.elements();
prefix += “\t”;
for (Element e : childNodes) {
readNode(e, prefix);
}
}
2 通过辅助类的形式
public static void read2() {
try {
SAXReader reader = new SAXReader();
InputStream in = TestDom4j.class.getClassLoader().getResourceAsStream(“text.xml”);
Document doc = reader.read(in);
doc.accept(td.new MyVistor());
} catch (DocumentException e) {
e.printStackTrace();
}
}
class MyVistor extends VisitorSupport {
public void visit(Attribute node) {
System.out.println(“Attibute: ” + node.getName() + “=” + node.getValue());
}
public void visit(Element node) {
if (node.isTextOnly()) {
System.out.println(“Element: ” + node.getName() + “=” + node.getText());
} else {
System.out.println(node.getName());
}
}
@Override
public void visit(ProcessingInstruction node) {
System.out.println(“PI:” + node.getTarget() + ” ” + node.getText());
}
}