这是一个例子:
//First create a Document
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("test.xml"));
//Init the xpath factory
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/company/employee";
//read a nodelist using xpath
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
Run Code Online (Sandbox Code Playgroud)
编辑 :
如果要使用SAX解析器,那么就不能使用Java的XPath对象,请参见https://docs.oracle.com/javase/7/docs/api/javax/xml/xpath/package-summary。 html
XPath 语言提供了一种简单、简洁的语法,用于从 XML 文档中选择节点。XPath 还提供了将 XML 文档对象模型 (DOM) 树中的节点转换为布尔值、双精度值或字符串值的规则。XPath是W3C定义的语言,也是W3C官方推荐的语言;W3C 托管 XML 路径语言 (XPath) 1.0 版规范。
XPath 于 1999 年作为 XSLT 和 XPointer 语言的补充而诞生,但最近作为一种独立语言变得流行,因为单个 XPath 表达式可用于替换多行 DOM API 代码。
如果您想使用 SAX,您可以查看此问题中详细说明的库:Is there any XPath handler for SAX model? 。
尽管 XPath 的机制并不真正适合 SAX。事实上,使用 SAX 解析器不会在内存中创建 XML 树。因此,您无法有效地使用 XPath,因为它看不到未加载的节点。
归档时间: |
|
查看次数: |
2974 次 |
最近记录: |