@Test
public void convertTest(){
try {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/xml/parse/stus.xml"));
//法一
String t=document.asXML();
System.out.println("读取完毕:\n"+t);
Element rootElm = document.getRootElement();
System.out.println("rootElm.getName()--->" + rootElm.getName());
List<?> nodes = rootElm.elements("stu");
System.out.println("第一种方法读元素stu的个数为:"+nodes.size());
System.out.println("rootElm.element(\"address\")--->" + rootElm.element("stu").element("address").getText());
System.out.println("=================================================");
//法二
HashMap<String, String> map = new HashMap<String, String>();
map.put("design",rootElm.getNamespaceURI());
// 创建解析路径,就是在普通的解析路径前加上map里的key值
XPath xPath = document.createXPath("//design:stu/design:name");
xPath.setNamespaceURIs(map);
List<Node> nodes2 = xPath.selectNodes(document);
System.out.println("第二种方法读取元素age的个数为:"+nodes2.size());
for (Node node : nodes2) {
System.out.println("node.getName()===" + node.getName());
System.out.println("node.getText()===" + node.getText());
}
} catch (Exception e) {
e.printStackTrace();
}
}
需要JAR包:dom4j.jar; jaxen.jar
xml文件
<?xml version="1.0" encoding="UTF-8"?>
<stus
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.example.org/stus"
xsi:schemaLocation="http://www.example.org/stus stus.xsd"
>
<stu id="123">
<name>张三</name>
<age>18</age>
<address>无为0309</address>
</stu>
<stu>
<name>李四</name>
<age>28</age>
<address>岐山</address>
</stu>
<stu>
<name>王五</name>
<!-- <age>32</age> -->
<address>北京</address>
</stu>
</stus>