// 1.通过DocumentBuilderFactor创建解析工厂
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
// 2.通过工厂获得解析器
DocumentBuilder builder = builderFactory.newDocumentBuilder();
// 3.通过parser方法获取Document
Document document = builder.parse("conf/books.xml");
// 4.获取xpath对象
XPath xpath = XPathFactory.newInstance().newXPath();
// 5.获取bookstore节点下book属性category值为web下的第二个title节点的文本内容
String exp = "/bookstore/book[@category='web'][2]/title/text()";
String tit = (String) xpath.evaluate(exp, document,
XPathConstants.STRING);
System.out.println(tit);
// 获取bookstore节点下book属性category值为web的titile属性为en的节点内容
String expEn = "/bookstore/book[@category='web']/title[@lang ='en']/text()";
String titEN = (String) xpath.evaluate(expEn, document,
XPathConstants.STRING);
System.out.println(titEN);
// 获取bookstore下book属性category值为cooking的title的lang属性的值
String expLan = "/bookstore/book[@category='cooking']/title/@lang";
String lang = (String) xpath.evaluate(expLan, document,
XPathConstants.STRING);
System.out.println(lang);