sql是数据库的结构查询语言,xpath是xml文件的查询语言。
package xpath;import java.io.IOException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.xpath.XPath;import javax.xml.xpath.XPathConstants;import javax.xml.xpath.XPathExpression;import javax.xml.xpath.XPathExpressionException;import javax.xml.xpath.XPathFactory;import org.w3c.dom.Document;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class Test { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // never forget this! DocumentBuilder builder; // 获得document builder = factory.newDocumentBuilder(); Document doc = builder .parse("E:\\TEST\\convertTest1\\2016\\201611\\20161107\\book.xml"); // 获得xpath XPathFactory xpathfactory = XPathFactory.newInstance(); XPath xpath = xpathfactory.newXPath(); // 查询语句 XPathExpression expr = xpath .compile("//book[author='Neal Stephenson']/title/text()"); // 查询得到结果 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()); } }}
关键在于查询语句