2010年5月25日 星期二

XML Xpath

XPath


book.xml
{{{


Snow Crash
Neal Stephenson
Spectra
0553380958
14.95



Burning Tower
Larry Niven
Jerry Pournelle
Pocket
0743416910
5.99



Zodiac
Neal Stephenson
Spectra
0553573862
7.50





}}}



XPathExample.java
{{{

import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;

public class XPathExample {

public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("Flu.xml");

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr
// = xpath.compile("//book[author='Neal Stephenson']/title/text()");
= xpath.compile("//log/attribute::fileName");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
expr
// = xpath.compile("//book[author='Neal Stephenson']/title/text()");
= xpath.compile("//logTree/attribute::fileName");
result = expr.evaluate(doc, XPathConstants.NODESET);
nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}

}
}}}



///Reference

http://www.w3schools.com/xpath/xpath_axes.asp

沒有留言:

張貼留言