XML.png
使用xpath解析xml文档!!
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
/**
使用JUnit进行单元测试
*/
public class DemoXPath {
private Document document; //声明一个文档对象
/**
在每个测试方法前执行
*/
@Before
public void init() throws DocumentException {
InputStream inputStream = DemoXPath.class.getResourceAsStream("/Contact.xml");
document = new SAXReader().read(inputStream);
}
/**
每个测试方法可以直接使用document对象
绝对路径
*/
@Test
public void testAbsolutePath() {
String xpath = "/contactList/contact/name";
//得到第一个name元素,父元素转成子元素
Element node = (Element) document.selectSingleNode(xpath);
System.out.println(node.getText());
//得到多个元素
List<Node> nodes = document.selectNodes(xpath);
for (Node node1 : nodes) {
Element element = (Element) node1;
System.out.println(element.getText());
}
}
/**
相对路径
*/
@Test
public void testRelativePath() {
//得到contactList元素
Node node = document.selectSingleNode("/contactList");
//得到子元素,注:node也有这两个方法, . 表示当前路径
Element element = (Element) node.selectSingleNode("./contact/name");
System.out.println(element.getText());
}
/**
全文搜索
*/
@Test
public void testGlobalSearch() {
List<Node> nodes = document.selectNodes("//email");
for (Node node : nodes) {
Element element = (Element) node;
System.out.println(element.getText());
}
}
/**
属性查找
*/
@Test
public void testAttributeFind() {
//得到的属性集合
/*List<Node> nodes = document.selectNodes("//@id");
for (Node node : nodes) {
Attribute attribute = (Attribute) node;
System.out.println("属性名:" + attribute.getName() + ",属性值:" + attribute.getValue());
}*/
//得到包含属性id的contact元素
/*List<Node> nodeList = document.selectNodes("//contact[@id]");
for (Node node : nodeList) {
Element element = (Element) node;
System.out.println(element);
}*/
//得到属性id=3的元素
Node node = document.selectSingleNode("//contact[@id=3]");
System.out.println(node);
}
}