发布网友 发布时间:2024-10-24 05:27
共1个回答
热心网友 时间:2024-11-14 21:53
先将 dom4j-1.6.jar 和 jaxen-1.1-beta-4.jar 加入到 CLASSPATH
1.xml:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<a>
<b>
<c>test1</c>
</b>
</a>
<a>
<c>test2</c>
</a>
</root>
TestXpath.java:
public static void main(String[] args) throws DocumentException {
SAXReader reader = new SAXReader();
Document doc = reader.read(new File("d:\\1.xml"));
Element root = doc.getRootElement();
Element ec = (Element)root.selectSingleNode("//c"); //查找根元素下的第一个 c 节点
System.out.println(ec.getTextTrim()); //print "test1"
List ecList = root.selectNodes("//c"); //查找文档中所有的 c 节点
/*
* print
*
* test1
* test2
*
* */
for(Iterator iterator = ecList.iterator(); iterator.hasNext(); )
{
Element element = (Element)iterator.next();
System.out.println(element.getTextTrim());
}
}