[b]books.xml[/b]
[b]基于java提供的API使用XPath处理XML[/b]
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
[b]基于java提供的API使用XPath处理XML[/b]
package com.hqh.stax;
import java.io.InputStream;
import javax.xml.crypto.NodeSetData;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class TestXPath {
@Test
public void testXPath() {
InputStream is = null;
try {
// 将xml以流才形式进行加载
is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("books.xml");
//构建文檔对象
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
// 将xml的输入流解析为一个dom对象
Document doc = builder.parse(is);
//創建XPath對象
XPath xpath = XPathFactory.newInstance().newXPath();
//第一個參數:xpath表達式;第二個參數:文檔源;第三個參數:返回類型
NodeList nodeList = (NodeList)xpath.evaluate("//book[@category='WEB']", doc, XPathConstants.NODESET);
//輸出屬性為WEB的book所有信息[將輸出該節點下的所有信息]
for(int i=0;i<nodeList.getLength();i++) {
Node node = nodeList.item(i);
System.out.println(node.getTextContent());
}
/* 結果:
XQuery Kick Start
James McGovern
Per Bothner
Kurt Cagle
James Linn
Vaidyanathan Nagarajan
2003
49.99
Learning XML
Erik T. Ray
2003
39.95*/
//輸出屬性為'WEB'的book的title信息
for(int i=0;i<nodeList.getLength();i++) {
Node node = nodeList.item(i);
Element element = (Element)node;
Node subNode = element.getElementsByTagName("title").item(0);
System.out.println(subNode.getTextContent());
}
/* 結果:
XQuery Kick Start
Learning XML*/
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}