Use XPath 到查询 XML documents
XPath navigates XML trees 具有路径 expressions, predicates, 和函数. Learn absolute 和 relative paths, wildcards, 和常见函数.
- 1
XPath expressions 选择 nodes 从 XML 树: /根/子 selects 所有子 elements, //元素 selects 任何地方, [@attr="值"] filters 通过属性, 文本() extracts 文本内容, * 是 wildcard. XPath 1.0 是 universally supported; XPath 2.0+ adds typing 和更多函数.
- 2 JSONPath 查询器 →
Use JSONPath ( JSON equivalent 的 XPath) 到查询 JSON converted 从 XML. 第一转换 XML 到 JSON, 然后 use JSONPath expressions like $.根.子[?(@.attr=="值")]. 此是 two-步骤 alternative 到 direct XPath.
- 3 XML 格式化器 →
格式化 the XML to understand its structure before writing XPath expressions. Indentation reveals the hierarchy, making it easier to construct correct paths. Verify your XPath by checking which nodes it selects.
- 4
常见 XPath patterns: /bookstore/book[1] (第一 book), /bookstore/book[price>35] (过滤通过子 值), //title (所有 titles 任何地方), 数量(//book) (数量 books), //book/@类别 (属性 values). Use predicates [...] 为 filtering 和函数 like 文本(), contains(), starts-with().
常见问题
- XPath vs CSS selectors?
- CSS selectors 工作开 HTML/XML elements (simpler, limited). XPath 是更多 powerful: 能够选择通过文本内容, use 函数, navigate 到父/ancestor, 和处理 namespaces. Use CSS selectors 为简单 HTML queries; use XPath 为复杂 XML 或当 CSS 是 insufficient.
- XPath 1.0 vs 2.0 vs 3.0?
- XPath 1.0 是 universally supported (browsers, libxml). XPath 2.0 adds sequences, richer 类型系统, 更多函数 — supported 通过 Saxon. XPath 3.0 adds 动态 evaluation. 为 web/browser use, stick 具有 1.0. 为服务器-边 XML 过程具有 Saxon, use 2.0+.