dom4j测试

时间:2021-05-06 16:26:24

book.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<name>java</name>
<price>25</price>
</book>

<book>
<name>php</name>
<price>30</price>
</book>
</books>

Test.class

@Test
public void test4(){
SAXReader sr = new SAXReader();
try {
Document doc = sr.read("src/book.xml");
Element root = doc.getRootElement();
/*Iterator<Element> iterator = root.elementIterator();
while(iterator.hasNext()){
Element element = iterator.next();
Element name = element.element("name");
System.out.println(name.getText());
}*/
test5(root);
} catch (DocumentException e) {
e.printStackTrace();
}
}

public void test5(Element element){
short nodeType = element.getNodeType();
Iterator iterator = element.elementIterator();
while(iterator.hasNext()){
element = (Element)iterator.next();
System.out.println(element.getName()+":"+element.getText().trim());
test5(element);
}
}