Xpath解析xml其实最主要的是查找xml文档中信息,而且不需要了解xml文档结构

package com.huawei.xml;

import java.io.InputStream;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;

/**
* @author Administrator
*
* 测试XPath
*/
public class TestXPathParser {

public static void main(String[] args) throws Exception{

//XPath表达式是用 XPathExpression来表示的
//所以要先得到这个类的实例 因为它是一个接口 所以不能直接得到实例

//构建document
InputStream in = TestJDOMParser.class.getClassLoader().getResourceAsStream("com/huawei/resources/Users.xml");
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);


//通过工厂去得到一个接口的实例
XPathFactory factory = XPathFactory.instance();

//编译表达式
XPathExpression<?> xpath = factory.compile("//User");
//执行表达式
List<?> list = xpath.evaluate(doc);

for(Object o:list){
Element e = (Element) o;
System.out.println(e.getText());
System.out.println(e.getAttributeValue("id"));
}

System.out.println(list.size());

}
}