掌握XPath命名空间前缀技巧 轻松解决复杂XML查询难题与常见错误规避

引言:XPath命名空间的重要性
在现代XML文档处理中,命名空间(Namespace)是一个至关重要的概念。随着XML在Web服务、配置文件、数据交换等领域的广泛应用,掌握XPath命名空间前缀技巧变得愈发重要。许多开发者在处理复杂XML查询时经常遇到命名空间相关的问题,导致查询失败或返回意外结果。
命名空间的主要作用是避免元素名称冲突。当不同的XML文档或同一文档的不同部分使用相同的元素名称但具有不同含义时,命名空间通过URI来区分它们。例如,一个文档可能同时包含来自XHTML和SVG命名空间的
<br /> 元素,它们虽然名称相同,但语义完全不同。<br /> 在XPath中,命名空间的处理方式与普通元素略有不同。XPath 1.0和2.0对命名空间的支持机制也有所区别,这增加了学习的复杂性。本文将深入探讨XPath命名空间前缀的使用技巧,帮助您轻松解决复杂XML查询难题,并规避常见错误。<br /> 理解XML命名空间基础<br /> 什么是XML命名空间?<br /> XML命名空间是一个通过URI标识的元素和属性名称的集合。URI的作用是提供唯一性,而不是指向实际的网页。例如:<br /> <root xmlns:ns1="http://example.com/ns1" xmlns:ns2="http://example.com/ns2"><br /> <ns1:item>Item 1</ns1:item><br /> <ns2:item>Item 2</ns2:item><br /> </root><br /> 在这个例子中,<br /> ns1:item<br /> 和<br /> ns2:item<br /> 是完全不同的元素,尽管它们的本地名称都是”item”。<br /> 命名空间声明<br /> 命名空间通过<br /> xmlns<br /> 属性声明:<br /> 带前缀的命名空间:<br /> xmlns:prefix=”URI”<br /> 默认命名空间:<br /> xmlns=”URI”<br /> 默认命名空间会影响所有无前缀的元素,但不会影响属性(属性始终无命名空间,除非显式指定)。<br /> 命名空间在XPath中的特殊性<br /> XPath在处理命名空间时有一个关键特点:<br /> XPath表达式中的元素名称不会自动继承XML文档中的命名空间上下文<br /> 。这意味着在XPath中,您必须显式地处理命名空间前缀,即使XML文档中使用了默认命名空间。<br /> XPath命名空间处理机制<br /> XPath 1.0 vs XPath 2.0+<br /> XPath 1.0和2.0在命名空间处理上有重要区别:<br /> XPath 1.0<br /> :<br /> 需要通过<br /> local-name()<br /> 和<br /> namespace-uri()<br /> 函数来绕过前缀问题<br /> 或者使用<br /> namespace::<br /> 轴来动态匹配命名空间<br /> XPath 2.0+<br /> :<br /> 支持更直观的命名空间前缀绑定<br /> 可以在XPath引擎中注册命名空间前缀<br /> 命名空间轴(namespace::)<br /> XPath提供了一个特殊的轴<br /> namespace::<br /> ,可以用来访问元素的命名空间。例如:<br /> //namespace::*<br /> 这个表达式会返回当前上下文中所有可用的命名空间节点。<br /> 在不同环境中处理XPath命名空间<br /> 1. 在编程语言中处理命名空间<br /> Python (lxml库)<br /> from lxml import etree</p> <p># XML文档包含命名空间<br /> xml_data = “””<br /> <root xmlns:ns1="http://example.com/ns1" xmlns:ns2="http://example.com/ns2"><br /> <ns1:item id="1">Item 1</ns1:item><br /> <ns2:item id="2">Item 2</ns2:item><br /> <item id="3">Item 3</item><br /> </root><br /> “””</p> <p># 解析XML<br /> root = etree.fromstring(xml_data.encode(‘utf-8′))</p> <p># 方法1:使用local-name()和namespace-uri()(XPath 1.0兼容)<br /> # 这种方法适用于任何XPath版本,但表达式较复杂<br /> items1 = root.xpath(“//*[local-name()=’item’ and namespace-uri()=’http://example.com/ns1′]”)<br /> print(“方法1结果:”, [item.text for item in items1])</p> <p># 方法2:在lxml中注册命名空间前缀(推荐)<br /> nsmap = {<br /> ‘ns1’: ‘http://example.com/ns1’,<br /> ‘ns2’: ‘http://example.com/ns2′<br /> }<br /> items2 = root.xpath(“//ns1:item”, namespaces=nsmap)<br /> print(“方法2结果:”, [item.text for item in items2])</p> <p># 方法3:使用通配符匹配命名空间<br /> items3 = root.xpath(“//*[namespace-uri()=’http://example.com/ns1′ and local-name()=’item’]”)<br /> print(“方法3结果:”, [item.text for item in items3])</p> <p># 方法4:处理默认命名空间<br /> xml_with_default = “””<br /> <root xmlns="http://example.com/default"><br /> <item>Default Item</item><br /> <ns1:item xmlns:ns1="http://example.com/ns1">NS1 Item</ns1:item><br /> </root><br /> “””<br /> root_default = etree.fromstring(xml_with_default.encode(‘utf-8’))</p> <p># 默认命名空间也需要注册<br /> nsmap_default = {<br /> ‘def’: ‘http://example.com/default’,<br /> ‘ns1’: ‘http://example.com/ns1’<br /> }<br /> default_items = root_default.xpath(“//def:item”, namespaces=nsmap_default)<br /> print(“默认命名空间结果:”, [item.text for item in default_items])<br /> Java (JAXB/DOM)<br /> import javax.xml.parsers.DocumentBuilder;<br /> import javax.xml.parsers.DocumentBuilderFactory;<br /> import javax.xml.xpath.XPath;<br /> import javax.xml.xpath.XPathConstants;<br /> import javax.xml.xpath.XPathFactory;<br /> import org.w3c.dom.Document;<br /> import org.w3c.dom.NodeList;<br /> import java.io.StringReader;<br /> import org.xml.sax.InputSource;</p> <p>public class XPathNamespaceExample {<br /> public static void main(String[] args) throws Exception {<br /> String xml = “””<br /> <root xmlns:ns1="http://example.com/ns1" xmlns:ns2="http://example.com/ns2"><br /> <ns1:item id="1">Item 1</ns1:item><br /> <ns2:item id="2">Item 2</ns2:item><br /> <item id="3">Item 3</item><br /> </root><br /> “””;</p> <p> DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();<br /> factory.setNamespaceAware(true);<br /> DocumentBuilder builder = factory.newDocumentBuilder();<br /> Document doc = builder.parse(new InputSource(new StringReader(xml)));</p> <p> XPath xpath = XPathFactory.newInstance().newXPath();</p> <p> // 方法1:使用local-name()和namespace-uri()<br /> String expression1 = “//*[local-name()=’item’ and namespace-uri()=’http://example.com/ns1′]”;<br /> NodeList nodes1 = (NodeList) xpath.evaluate(expression1, doc, XPathConstants.NODESET);<br /> System.out.println(“方法1结果:”);<br /> for (int i = 0; i < nodes1.getLength(); i++) { System.out.println(nodes1.item(i).getTextContent()); } // 方法2:使用命名空间上下文(推荐) xpath.setNamespaceContext(new javax.xml.namespace.NamespaceContext() { public String getNamespaceURI(String prefix) { switch (prefix) { case "ns1": return "http://example.com/ns1"; case "ns2": return "http://example.com/ns2"; case "def": return "http://example.com/default"; default: return null; } } public String getPrefix(String namespaceURI) { return null; } public java.util.Iterator<String> getPrefixes(String namespaceURI) { return null; }<br /> });</p> <p> String expression2 = “//ns1:item”;<br /> NodeList nodes2 = (NodeList) xpath.evaluate(expression2, doc, XPathConstants.NODESET);<br /> System.out.println(“\n方法2结果:”);<br /> for (int i = 0; i < nodes2.getLength(); i++) { System.out.println(nodes2.item(i).getTextContent()); } } } JavaScript (浏览器DOM) // XML文档 const xmlString = ` <root xmlns:ns1="http://example.com/ns1" xmlns:ns2="http://example.com/ns2"><br /> <ns1:item id="1">Item 1</ns1:item><br /> <ns2:item id="2">Item 2</ns2:item><br /> <item id="3">Item 3</item><br /> </root><br /> `;</p> <p>// 解析XML<br /> const parser = new DOMParser();<br /> const xmlDoc = parser.parseFromString(xmlString, “text/xml”);</p> <p>// 方法1:使用local-name()和namespace-uri()<br /> const items1 = xmlDoc.evaluate(<br /> “//*[local-name()=’item’ and namespace-uri()=’http://example.com/ns1′]”,<br /> xmlDoc,<br /> null,<br /> XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,<br /> null<br /> );</p> <p>console.log(“方法1结果:”);<br /> for (let i = 0; i < items1.snapshotLength; i++) { console.log(items1.snapshotItem(i).textContent); } // 方法2:在浏览器中,XPath 2.0不支持命名空间前缀绑定 // 需要使用NSResolver const nsResolver = (prefix) => {<br /> const ns = {<br /> ‘ns1’: ‘http://example.com/ns1’,<br /> ‘ns2’: ‘http://example.com/ns2’<br /> };<br /> return ns[prefix] || null;<br /> };</p> <p>const items2 = xmlDoc.evaluate(<br /> “//ns1:item”,<br /> xmlDoc,<br /> nsResolver,<br /> XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,<br /> null<br /> );</p> <p>console.log(“\n方法2结果:”);<br /> for (let i = 0; i < items2.snapshotLength; i++) { console.log(items2.snapshotItem(i).textContent); } // 方法3:使用通配符(XPath 1.0兼容) const items3 = xmlDoc.evaluate( "//*[namespace-uri()='http://example.com/ns1' and local-name()='item']", xmlDoc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ); console.log("\n方法3结果:"); for (let i = 0; i < items3.snapshotLength; i++) { console.log(items3.snapshotItem(i).textContent); } 2. 在XSLT中处理命名空间 <?xml version="1.0" encoding="UTF-8"?><br /> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns1="http://example.com/ns1" xmlns:ns2="http://example.com/ns2"></p> <p> <xsl:output method="xml" indent="yes"/></p> <p> <!-- 匹配特定命名空间的元素 --><br /> <xsl:template match="ns1:item"><br /> <output><br /> <xsl:value-of select="."/><br /> </output><br /> </xsl:template></p> <p> <!-- 使用XPath表达式中的命名空间 --><br /> <xsl:template match="/"><br /> <results><br /> <!-- 直接使用前缀 --><br /> <ns1-items><br /> <xsl:for-each select="//ns1:item"><br /> <item><xsl:value-of select="."/></item><br /> </xsl:for-each><br /> </ns1-items></p> <p> <!-- 使用local-name()和namespace-uri() --><br /> <ns1-items-alt><br /> <xsl:for-each select="//*[local-name()='item' and namespace-uri()='http://example.com/ns1']"><br /> <item><xsl:value-of select="."/></item><br /> </xsl:for-each><br /> </ns1-items-alt></p> <p> <!-- 处理默认命名空间 --><br /> <default-items><br /> <xsl:for-each select="//*[local-name()='item' and namespace-uri()='http://example.com/default']"><br /> <item><xsl:value-of select="."/></item><br /> </xsl:for-each><br /> </default-items><br /> </results><br /> </xsl:template><br /> </xsl:stylesheet><br /> 3. 在XQuery中处理命名空间<br /> xquery version “1.0”;</p> <p>declare namespace ns1 = “http://example.com/ns1”;<br /> declare namespace ns2 = “http://example.com/ns2”;</p> <p>let $xml :=<br /> <root xmlns:ns1="http://example.com/ns1" xmlns:ns2="http://example.com/ns2"><br /> <ns1:item id="1">Item 1</ns1:item><br /> <ns2:item id="2">Item 2</ns2:item><br /> <item id="3">Item 3</item><br /> </root></p> <p>return (<br /> (: 方法1:使用声明的前缀 🙂<br /> $xml//ns1:item,</p> <p> (: 方法2:使用local-name()和namespace-uri() 🙂<br /> $xml//*[local-name()=’item’ and namespace-uri()=’http://example.com/ns1′]<br /> )<br /> 常见错误及规避策略<br /> 错误1:忘记处理命名空间<br /> 问题<br /> :直接使用元素名称查询,忽略命名空间。<br /> # 错误示例<br /> items = root.xpath(“//item”) # 返回空列表,因为实际元素是ns1:item<br /> 解决方案<br /> :<br /> # 正确方式1:注册命名空间<br /> items = root.xpath(“//ns1:item”, namespaces={‘ns1’: ‘http://example.com/ns1′})</p> <p># 正确方式2:使用local-name()<br /> items = root.xpath(“//*[local-name()=’item’]”)<br /> 错误2:混淆前缀和命名空间URI<br /> 问题<br /> :认为前缀在不同文档中必须相同。<br /> <!-- 文档A --><br /> <root xmlns:ns1="http://example.com/ns1"><br /> <ns1:item>…</ns1:item><br /> </root></p> <p><!-- 文档B --><br /> <root xmlns:custom="http://example.com/ns1"><br /> <custom:item>…</custom:item><br /> </root><br /> 解决方案<br /> :始终基于命名空间URI而不是前缀进行匹配。<br /> # 正确做法:匹配命名空间URI<br /> def find_items_by_namespace(root, namespace_uri):<br /> return root.xpath(f”//*[namespace-uri()='{namespace_uri}’ and local-name()=’item’]”)<br /> 错误3:默认命名空间处理不当<br /> 问题<br /> :默认命名空间的元素在XPath中需要特殊处理。<br /> <root xmlns="http://example.com/default"><br /> <item>…</item><br /> </root><br /> 解决方案<br /> :<br /> # 必须为默认命名空间注册前缀<br /> nsmap = {‘def’: ‘http://example.com/default’}<br /> items = root.xpath(“//def:item”, namespaces=nsmap)<br /> 错误4:属性命名空间处理<br /> 问题<br /> :属性的命名空间处理与元素不同。<br /> <root xmlns:ns1="http://example.com/ns1"><br /> <item ns1:attr="value">…</item><br /> </root><br /> 解决方案<br /> :<br /> # 属性需要显式指定命名空间<br /> items = root.xpath(“//item[@ns1:attr]”, namespaces={‘ns1’: ‘http://example.com/ns1′})<br /> 错误5:XPath版本兼容性问题<br /> 问题<br /> :XPath 2.0+的高级功能在XPath 1.0中不可用。<br /> 解决方案<br /> :<br /> # 使用XPath 1.0兼容的方法<br /> # 不使用://ns1:item[fn:year-from-dateTime(@timestamp)]<br /> # 而是使用://ns1:item[substring(@timestamp,1,4)=’2023′]<br /> 高级技巧与最佳实践<br /> 1. 动态命名空间处理<br /> 当处理未知或动态命名空间时:<br /> def find_elements_with_dynamic_namespace(root, element_name, namespace_uri):<br /> “””在任意命名空间中查找元素”””<br /> return root.xpath(<br /> f”//*[namespace-uri()='{namespace_uri}’ and local-name()='{element_name}’]”<br /> )</p> <p># 使用示例<br /> items = find_elements_with_dynamic_namespace(root, ‘item’, ‘http://example.com/ns1′)<br /> 2. 命名空间通配符<br /> 使用通配符匹配任意命名空间:<br /> # 匹配所有命名空间下的item元素<br /> all_items = root.xpath(“//*[local-name()=’item’]”)</p> <p># 匹配特定前缀的元素(不关心具体URI)<br /> ns1_items = root.xpath(“//ns1:*”, namespaces={‘ns1’: ‘http://example.com/ns1’})<br /> 3. 命名空间轴高级用法<br /> # 获取元素的所有命名空间<br /> namespaces = root.xpath(“//namespace::*”)</p> <p># 获取特定元素的命名空间<br /> ns1_element = root.xpath(“//ns1:item[1]”, namespaces={‘ns1’: ‘http://example.com/ns1’})[0]<br /> element_namespaces = ns1_element.xpath(“namespace::*”)<br /> 4. 性能优化<br /> # 预编译XPath表达式(适用于重复查询)<br /> from lxml import etree</p> <p># 注册命名空间<br /> nsmap = {‘ns1’: ‘http://example.com/ns1’, ‘ns2’: ‘http://example.com/ns2’}</p> <p># 编译XPath<br /> xpath_ns1_item = etree.XPath(“//ns1:item”, namespaces=nsmap)<br /> xpath_ns2_item = etree.XPath(“//ns2:item”, namespaces=nsmap)</p> <p># 重复使用<br /> items1 = xpath_ns1_item(root)<br /> items2 = xpath_ns2_item(root)<br /> 5. 处理多个命名空间<br /> # 复杂XML文档可能有多个命名空间<br /> complex_xml = “””<br /> <root xmlns:ns1="http://example.com/ns1" xmlns:ns2="http://example.com/ns2" xmlns:ns3="http://example.com/ns3"><br /> <ns1:container><br /> <ns2:item>Item A</ns2:item><br /> </ns1:container><br /> <ns3:item>Item B</ns3:item><br /> </root><br /> “””</p> <p>root = etree.fromstring(complex_xml.encode(‘utf-8’))</p> <p># 同时查询多个命名空间<br /> nsmap = {<br /> ‘ns1’: ‘http://example.com/ns1’,<br /> ‘ns2’: ‘http://example.com/ns2’,<br /> ‘ns3’: ‘http://example.com/ns3’<br /> }</p> <p># 查询ns2:item,但只在ns1:container下<br /> items = root.xpath(“//ns1:container/ns2:item”, namespaces=nsmap)<br /> print([item.text for item in items]) # [‘Item A’]</p> <p># 查询所有命名空间下的item<br /> all_items = root.xpath(“//*[local-name()=’item’]”)<br /> print([item.text for item in all_items]) # [‘Item A’, ‘Item B’]<br /> 实际应用场景<br /> 场景1:SOAP Web服务响应处理<br /> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><br /> <soap:Body><br /> <GetUserResponse xmlns="http://example.com/user"><br /> <user><br /> <name>John Doe</name><br /> <email>john@example.com</email><br /> </user><br /> </GetUserResponse><br /> </soap:Body><br /> </soap:Envelope><br /> from lxml import etree</p> <p>soap_xml = “””…””” # 上面的XML</p> <p>root = etree.fromstring(soap_xml.encode(‘utf-8’))</p> <p># 注册所有命名空间<br /> nsmap = {<br /> ‘soap’: ‘http://schemas.xmlsoap.org/soap/envelope/’,<br /> ‘usr’: ‘http://example.com/user’<br /> }</p> <p># 提取用户信息<br /> name = root.xpath(“//usr:user/usr:name/text()”, namespaces=nsmap)[0]<br /> email = root.xpath(“//usr:user/usr:email/text()”, namespaces=nsmap)[0]<br /> 场景2:SVG文档处理<br /> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="40" fill="red" /> <text x="50" y="50" text-anchor="middle" fill="white">Hello</text> </svg><br /> svg_xml = “””…””” # 上面的XML</p> <p>root = etree.fromstring(svg_xml.encode(‘utf-8’))</p> <p># SVG使用默认命名空间,需要注册<br /> nsmap = {‘svg’: ‘http://www.w3.org/2000/svg’}</p> <p># 查找所有圆形元素<br /> circles = root.xpath(“//svg:circle”, namespaces=nsmap)<br /> for circle in circles:<br /> print(f”Circle at ({circle.get(‘cx’)}, {circle.get(‘cy’)})”)</p> <p># 查找文本内容<br /> text = root.xpath(“//svg:text/text()”, namespaces=nsmap)[0]<br /> print(f”Text content: {text}”)<br /> 场景3:配置文件处理<br /> <configuration xmlns="http://example.com/config" xmlns:db="http://example.com/database"><br /> <server><br /> <host>localhost</host> <port>8080</port> </server><br /> <db:connection><br /> <db:url>jdbc:mysql://localhost:3306/mydb</db:url><br /> <db:username>admin</db:username><br /> </db:connection><br /> </configuration><br /> config_xml = “””…””” # 上面的XML</p> <p>root = etree.fromstring(config_xml.encode(‘utf-8’))</p> <p>nsmap = {<br /> ‘cfg’: ‘http://example.com/config’,<br /> ‘db’: ‘http://example.com/database’<br /> }</p> <p># 提取服务器配置<br /> host = root.xpath(“//cfg:server/cfg:host/text()”, namespaces=nsmap)[0]<br /> port = root.xpath(“//cfg:server/cfg:port/text()”, namespaces=nsmap)[0]</p> <p># 提取数据库配置<br /> db_url = root.xpath(“//db:connection/db:url/text()”, namespaces=nsmap)[0]<br /> db_user = root.xpath(“//db:connection/db:username/text()”, namespaces=nsmap)[0]</p> <p>print(f”Server: {host}:{port}”)<br /> print(f”Database: {db_url} (user: {db_user})”)<br /> 调试技巧<br /> 1. 查看文档的命名空间<br /> def debug_namespaces(element):<br /> “””打印元素及其子元素的所有命名空间”””<br /> print(“Available namespaces:”)<br /> for ns in element.xpath(“namespace::*”):<br /> print(f” {ns.prefix}: {ns.uri}”)</p> <p> # 查看元素本身的命名空间<br /> print(f”\nElement namespace: {element.nsmap}”)</p> <p># 使用示例<br /> root = etree.fromstring(xml_string.encode(‘utf-8’))<br /> debug_namespaces(root)<br /> 2. 验证XPath表达式<br /> def test_xpath(root, expression, nsmap=None):<br /> “””测试XPath表达式并显示结果”””<br /> try:<br /> if nsmap:<br /> result = root.xpath(expression, namespaces=nsmap)<br /> else:<br /> result = root.xpath(expression)<br /> print(f”Expression: {expression}”)<br /> print(f”Result count: {len(result)}”)<br /> print(f”Results: {[r.text if hasattr(r, ‘text’) else str(r) for r in result]}”)<br /> return result<br /> except Exception as e:<br /> print(f”Error in expression ‘{expression}’: {e}”)<br /> return None</p> <p># 使用示例<br /> test_xpath(root, “//ns1:item”, {‘ns1’: ‘http://example.com/ns1’})<br /> 3. 常见错误模式识别<br /> def diagnose_xpath_issue(root, expression, nsmap=None):<br /> “””诊断XPath查询问题”””<br /> print(f”Diagnosing: {expression}”)</p> <p> # 检查1:表达式是否包含命名空间前缀<br /> if ‘:’ in expression and not nsmap:<br /> print(“⚠️ 表达式包含命名空间前缀但未提供nsmap”)</p> <p> # 检查2:尝试无命名空间版本<br /> if ‘:’ in expression:<br /> base_name = expression.split(‘:’)[-1]<br /> alt_expression = f”//*[local-name()='{base_name}’]”<br /> alt_result = root.xpath(alt_expression)<br /> print(f” Alternative (no ns): {len(alt_result)} results”)</p> <p> # 检查3:检查文档中的实际命名空间<br /> all_ns = root.xpath(“namespace::*”)<br /> print(f” Document namespaces: {[f'{ns.prefix}:{ns.uri}’ for ns in all_ns]}”)</p> <p> # 执行原始查询<br /> try:<br /> result = root.xpath(expression, namespaces=nsmap) if nsmap else root.xpath(expression)<br /> print(f” Final result: {len(result)} items”)<br /> return result<br /> except Exception as e:<br /> print(f” ❌ Error: {e}”)<br /> return None<br /> 总结<br /> 掌握XPath命名空间前缀技巧是处理复杂XML文档的关键能力。通过本文的详细讲解和大量实例,您应该已经了解了:<br /> 基础概念<br /> :XML命名空间的作用和XPath处理机制<br /> 核心技巧<br /> :在不同编程语言中正确处理命名空间的方法<br /> 常见错误<br /> :识别和规避命名空间相关问题的策略<br /> 高级应用<br /> :动态命名空间处理、性能优化等高级技巧<br /> 实际场景<br /> :SOAP、SVG、配置文件等真实世界的应用<br /> 记住以下关键点:<br /> 始终基于命名空间URI而不是前缀进行匹配<br /> 在XPath表达式中显式处理命名空间,不要依赖默认行为<br /> 使用<br /> local-name()<br /> 和<br /> namespace-uri()<br /> 作为XPath 1.0的兼容方案<br /> 在支持XPath 2.0+的环境中,优先使用命名空间前缀绑定<br /> 充分利用调试工具来理解和解决问题<br /> 通过实践这些技巧,您将能够轻松应对各种复杂的XML查询需求,避免常见的陷阱,并编写出健壮、高效的XML处理代码。</p> </div> <div class="wp-block-group has-global-padding is-layout-constrained wp-block-group-is-layout-constrained" style="margin-top:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--50)"> <div class="wp-block-group has-global-padding is-layout-constrained wp-block-group-is-layout-constrained"> <div style="height:var(--wp--preset--spacing--40)" aria-hidden="true" class="wp-block-spacer"> </div> <hr class="wp-block-separator has-text-color has-contrast-3-color has-alpha-channel-opacity has-contrast-3-background-color has-background is-style-wide" style="margin-bottom:var(--wp--preset--spacing--40)"/> <nav class="wp-block-group is-content-justification-space-between is-nowrap is-layout-flex wp-container-core-group-is-layout-2b923ac6 wp-block-group-is-layout-flex" style="padding-top:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40)" aria-label="Posts"> <div class="post-navigation-link-previous wp-block-post-navigation-link"><span class="wp-block-post-navigation-link__arrow-previous is-arrow-arrow" aria-hidden="true">←</span><a href="https://ziliao.tiaomu.com/114090464/" rel="prev"><span class="post-navigation-link__label">Previous: </span> <span class="post-navigation-link__title">如何制定高效SVN开发规范,提高团队协作效率</span></a></div> <div class="post-navigation-link-next wp-block-post-navigation-link"><a href="https://ziliao.tiaomu.com/114090466/" rel="next"><span class="post-navigation-link__label">Next: </span> <span class="post-navigation-link__title">掌握Python编程精髓,刘卫国经典教程电子版大揭秘</span></a><span class="wp-block-post-navigation-link__arrow-next is-arrow-arrow" aria-hidden="true">→</span></div> </nav> </div> </div> </main> <footer class="wp-block-template-part"> <div class="wp-block-group has-global-padding is-layout-constrained wp-block-group-is-layout-constrained" style="padding-top:var(--wp--preset--spacing--50);padding-bottom:var(--wp--preset--spacing--50)"> <div class="wp-block-columns alignwide is-layout-flex wp-container-core-columns-is-layout-3a88641f wp-block-columns-is-layout-flex"> <div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:30%"> <div class="wp-block-group is-vertical is-layout-flex wp-container-core-group-is-layout-831b2db5 wp-block-group-is-layout-flex"> <p class="wp-block-site-title has-medium-font-size"><a href="https://ziliao.tiaomu.com" target="_self" rel="home">资料库 – 中文知识库</a></p> </div> </div> <div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:20%"> </div> <div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:50%"> <div class="wp-block-group is-content-justification-space-between is-layout-flex wp-container-core-group-is-layout-cf54d0a6 wp-block-group-is-layout-flex"> <div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-d8dce8eb wp-block-group-is-layout-flex"> <h2 class="wp-block-heading has-medium-font-size has-body-font-family" style="font-style:normal;font-weight:600">About</h2> <div class="wp-block-group is-vertical is-layout-flex wp-container-core-group-is-layout-bce0c455 wp-block-group-is-layout-flex"> <nav style="font-style:normal;font-weight:400" class="has-small-font-size is-vertical wp-block-navigation is-layout-flex wp-container-core-navigation-is-layout-bce0c455 wp-block-navigation-is-layout-flex" aria-label="About"><ul style="font-style:normal;font-weight:400" class="wp-block-navigation__container has-small-font-size is-vertical wp-block-navigation" aria-label="About"><li class="wp-block-navigation-item wp-block-navigation-link"><a class="wp-block-navigation-item__content" href="#"><span class="wp-block-navigation-item__label">Team</span></a></li><li class="wp-block-navigation-item wp-block-navigation-link"><a class="wp-block-navigation-item__content" href="#"><span class="wp-block-navigation-item__label">History</span></a></li><li class="wp-block-navigation-item wp-block-navigation-link"><a class="wp-block-navigation-item__content" href="#"><span class="wp-block-navigation-item__label">Careers</span></a></li></ul></nav> </div> </div> <div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-d8dce8eb wp-block-group-is-layout-flex"> <h2 class="wp-block-heading has-medium-font-size has-body-font-family" style="font-style:normal;font-weight:600">Privacy</h2> <div class="wp-block-group is-vertical is-layout-flex wp-container-core-group-is-layout-bce0c455 wp-block-group-is-layout-flex"> <nav style="font-style:normal;font-weight:400" class="has-small-font-size is-vertical wp-block-navigation is-layout-flex wp-container-core-navigation-is-layout-bce0c455 wp-block-navigation-is-layout-flex" aria-label="Privacy"><ul style="font-style:normal;font-weight:400" class="wp-block-navigation__container has-small-font-size is-vertical wp-block-navigation" aria-label="Privacy"><li class="wp-block-navigation-item wp-block-navigation-link"><a class="wp-block-navigation-item__content" href="#"><span class="wp-block-navigation-item__label">Privacy Policy</span></a></li><li class="wp-block-navigation-item wp-block-navigation-link"><a class="wp-block-navigation-item__content" href="#"><span class="wp-block-navigation-item__label">Terms and Conditions</span></a></li><li class="wp-block-navigation-item wp-block-navigation-link"><a class="wp-block-navigation-item__content" href="#"><span class="wp-block-navigation-item__label">Contact Us</span></a></li></ul></nav> </div> </div> <div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-d8dce8eb wp-block-group-is-layout-flex"> <h2 class="wp-block-heading has-medium-font-size has-body-font-family" style="font-style:normal;font-weight:600">Social</h2> <div class="wp-block-group is-vertical is-layout-flex wp-container-core-group-is-layout-bce0c455 wp-block-group-is-layout-flex"> <nav style="font-style:normal;font-weight:400" class="has-small-font-size is-vertical wp-block-navigation is-layout-flex wp-container-core-navigation-is-layout-bce0c455 wp-block-navigation-is-layout-flex" aria-label="Social Media"><ul style="font-style:normal;font-weight:400" class="wp-block-navigation__container has-small-font-size is-vertical wp-block-navigation" aria-label="Social Media"><li class="wp-block-navigation-item wp-block-navigation-link"><a class="wp-block-navigation-item__content" href="#"><span class="wp-block-navigation-item__label">Facebook</span></a></li><li class="wp-block-navigation-item wp-block-navigation-link"><a class="wp-block-navigation-item__content" href="#"><span class="wp-block-navigation-item__label">Instagram</span></a></li><li class="wp-block-navigation-item wp-block-navigation-link"><a class="wp-block-navigation-item__content" href="#"><span class="wp-block-navigation-item__label">Twitter/X</span></a></li></ul></nav> </div> </div> </div> </div> </div> <div class="wp-block-group alignwide is-layout-flow wp-block-group-is-layout-flow" style="padding-top:var(--wp--preset--spacing--50);padding-bottom:0"> <p class="has-contrast-2-color has-text-color has-link-color has-small-font-size wp-elements-1 wp-block-paragraph"> Designed with <a href="https://wordpress.org" rel="nofollow">WordPress</a> </p> </div> </div> </footer> </div> <script type="speculationrules"> {"prefetch":[{"source":"document","where":{"and":[{"href_matches":"/*"},{"not":{"href_matches":["/wp-*.php","/wp-admin/*","/wp-content/uploads/*","/wp-content/*","/wp-content/plugins/*","/wp-content/themes/twentytwentyfour/*","/*\\?(.+)"]}},{"not":{"selector_matches":"a[rel~=\"nofollow\"]"}},{"not":{"selector_matches":".no-prefetch, .no-prefetch a"}}]},"eagerness":"conservative"}]} </script> <script data-wp-router-options="{"loadOnClientNavigation":true}" fetchpriority="low" id="@wordpress/block-library/navigation/view-js-module" src="https://ziliao.tiaomu.com/wp-includes/js/dist/script-modules/block-library/navigation/view.min.js?ver=1bf28ded04f9f188bdcb" type="module"></script> <script id="wp-emoji-settings" type="application/json"> {"baseUrl":"https://s.w.org/images/core/emoji/17.0.2/72x72/","ext":".png","svgUrl":"https://s.w.org/images/core/emoji/17.0.2/svg/","svgExt":".svg","source":{"concatemoji":"https://ziliao.tiaomu.com/wp-includes/js/wp-emoji-release.min.js?ver=7.1.5"}} </script> <script type="module"> /*! This file is auto-generated */ var e="script#wp-emoji-settings",t=document.querySelector(e);if(!(t instanceof HTMLScriptElement))throw new Error("Element missing: "+e);const r=JSON.parse(t.text),s=(window._wpemojiSettings=r,"wpEmojiSettingsSupports"),o=["flag","emoji"];function i(e){try{var t={supportTests:e,timestamp:(new Date).valueOf()};sessionStorage.setItem(s,JSON.stringify(t))}catch(e){}}function c(e,t,n){e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(t,0,0);t=new Uint32Array(e.getImageData(0,0,e.canvas.width,e.canvas.height).data);e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(n,0,0);const r=new Uint32Array(e.getImageData(0,0,e.canvas.width,e.canvas.height).data);return t.every((e,t)=>e===r[t])}function p(e,t){e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(t,0,0);var n=e.getImageData(16,16,1,1);for(let e=0;e<n.data.length;e++)if(0!==n.data[e])return!1;return!0}function u(e,t,n,r){switch(t){case"flag":return n(e,"\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f","\ud83c\udff3\ufe0f\u200b\u26a7\ufe0f")?!1:!n(e,"\ud83c\udde8\ud83c\uddf6","\ud83c\udde8\u200b\ud83c\uddf6")&&!n(e,"\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f","\ud83c\udff4\u200b\udb40\udc67\u200b\udb40\udc62\u200b\udb40\udc65\u200b\udb40\udc6e\u200b\udb40\udc67\u200b\udb40\udc7f");case"emoji":return!r(e,"\ud83e\u1fac8")}return!1}function f(e,t,n,r){let a;const s=(a="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?new OffscreenCanvas(300,150):document.createElement("canvas")).getContext("2d",{willReadFrequently:!0}),o=(s.textBaseline="top",s.font="600 32px Arial",{});return e.forEach(e=>{o[e]=t(s,e,n,r)}),o}function a(e){var t=document.createElement("script");t.src=e,t.defer=!0,document.head.appendChild(t)}r.supports={everything:!0,everythingExceptFlag:!0},new Promise(t=>{let n=function(){try{var e=JSON.parse(sessionStorage.getItem(s));if("object"==typeof e&&"number"==typeof e.timestamp&&(new Date).valueOf()<e.timestamp+604800&&"object"==typeof e.supportTests)return e.supportTests}catch(e){}return null}();if(!n){if("undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas&&"undefined"!=typeof URL&&URL.createObjectURL&&"undefined"!=typeof Blob)try{var e="postMessage("+f.toString()+"("+[JSON.stringify(o),u.toString(),c.toString(),p.toString()].join(",")+"));",r=new Blob([e],{type:"text/javascript"});const a=new Worker(URL.createObjectURL(r),{name:"wpTestEmojiSupports"});return void(a.onmessage=e=>{i(n=e.data),a.terminate(),t(n)})}catch(e){}i(n=f(o,u,c,p))}t(n)}).then(e=>{for(const n in e)r.supports[n]=e[n],r.supports.everything=r.supports.everything&&r.supports[n],"flag"!==n&&(r.supports.everythingExceptFlag=r.supports.everythingExceptFlag&&r.supports[n]);var t;r.supports.everythingExceptFlag=r.supports.everythingExceptFlag&&!r.supports.flag,r.supports.everything||((t=r.source||{}).concatemoji?a(t.concatemoji):t.wpemoji&&t.twemoji&&(a(t.twemoji),a(t.wpemoji)))}); //# sourceURL=https://ziliao.tiaomu.com/wp-includes/js/wp-emoji-loader.min.js </script> <noscript><link rel="stylesheet" href="https://ziliao.tiaomu.com/wp-content/themes/abiz/assets/css/all.min.css?ver=6.5.1"></noscript> </body> </html>