解析 XML with namespaces
XML namespaces qualify 元素 names 到 avoid collisions. Learn xmlns 声明, 默认 vs prefixed namespaces, 和如何解析它们正确.
- 1
XML namespaces use URIs 到 disambiguate 元素 names. 命名空间是 declared 具有 xmlns="uri" (默认) 或 xmlns:prefix="uri" (prefixed). Elements 是然后 qualified: <prefix:元素>. 命名空间 URI 是 identifier — prefix 是仅 shorthand. Two elements 具有相同本地 name 但不同 namespaces 是不同 elements.
- 2 XML 格式化器 →
格式化 the XML to see namespace declarations clearly. The formatter shows which prefixes map to which URIs. Verify that all prefixed elements have a corresponding xmlns declaration in scope.
- 3 JSON 与 XML 互转器 →
将 namespaced XML to JSON. Namespace-qualified elements typically become prefixed keys: <ns:element> → "ns:element" or "{uri}element" depending on the converter. Understand your converter's namespace handling 转换为 query the correct keys
- 4
常见 namespaces: xmlns="http://www.w3.org/1999/xhtml" (XHTML), xmlns:svg="http://www.w3.org/2000/svg" (SVG), xmlns:atom="http://www.w3.org/2005/Atom" (Atom feeds). 当 parsing, 匹配开 命名空间 URI, 不 prefix — prefixes 能够是 reassigned. Use XPath 具有命名空间 resolvers 为 robust querying.
常见问题
- 为什么 use namespaces?
- 到组合 XML vocabularies 无 name collisions. 为示例, XHTML 和 SVG 两者有 <title> 元素 — namespaces distinguish <xhtml:title> 从 <svg:title>. 无 namespaces, parser cannot tell 它们 apart.
- 是 prefix significant?
- 否 — 命名空间 URI 是 identifier, 不 prefix. <foo:bar xmlns:foo="urn:x"> 和 <baz:bar xmlns:baz="urn:x"> 是相同元素. 当 comparing 或 querying, 总是 use URI, 不 prefix. Prefixes 是 arbitrary shorthand.