xml文件
books.xml
<inventory> <book year="2000"> <title>Thinking in Java</title> <author>TEST</author> <publisher>JQGYCBS</publisher> <isbn>80958</isbn> <price>98.95</price> </book> <book year="2005"> <title>ROR</title> <author>TEST</author> <publisher>DZGYCBS</publisher> <isbn>0743416910</isbn> <price>65.99</price> </book> <book year="1995"> <title>H</title> <author>King</author> <publisher>Sc</publisher> <isbn>0553862</isbn> <price>77.50</price> </book> </inventory>
java代码
package book;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Test {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("src/books.xml");
XPathFactory pathFactory = XPathFactory.newInstance();
XPath xpath = pathFactory.newXPath();
XPathExpression pathExpression = xpath
.compile("//book[author='TEST']/title/text()");
Object result = pathExpression.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
}