
使用命名空间导航 XML:SelectSingleNode 挑战
使用包含命名空间的 XML 文档时,.NET 中的标准 SelectSingleNode 方法可能会出现意外行为。 这是因为像 //Compile 这样的简单 XPath 表达式本身并不理解命名空间。
我们举个例子来说明一下:
<code class="language-xml"><project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<itemgroup>
<compile include="clsWorker.cs"/>
</itemgroup>
</project></code>尝试使用 <compile> 选择 xmldoc.SelectSingleNode("//Compile") 节点将返回 null。 命名空间声明 xmlns="http://schemas.microsoft.com/developer/msbuild/2003" 是罪魁祸首。
解决方案:利用XmlNamespaceManager
在命名空间 XML 中正确选择节点的关键是利用 XmlNamespaceManager 类。此类允许您显式定义命名空间前缀及其相应的 URI。
以下是修改代码的方法:
<code class="language-csharp">XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);
ns.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003");
XmlNode node = xmldoc.SelectSingleNode("//msbld:Compile", ns);</code>我们创建一个 XmlNamespaceManager,添加命名空间映射(“msbld”作为指定 URI 的前缀),然后将此管理器传递给 SelectSingleNode。 XPath 表达式 //msbld:Compile 现在可以正确识别定义的命名空间内的节点。 即使在复杂的命名空间 XML 结构中,这种方法也能确保准确的节点选择。
以上是XML命名空间如何影响'SelectSingleNode”以及如何正确选择节点?的详细内容。更多信息请关注PHP中文网其他相关文章!