【问题标题】:Whats wrong with my XPath?我的 XPath 有什么问题?
【发布时间】:2012-09-10 08:28:42
【问题描述】:

我尝试解析这个 XML 文件(来自Chirpy 的配置文件):

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns="urn:ChirpyConfig" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="urn:ChirpyConfig http://www.weirdlover.com/chirpy/chirp.xsd">
     <FileGroup Name="Built.debug.js" Minify="false">
        <File Path="jquery/jquery-1.7.2.js"/>
        <File Path="jquery.address/jquery.address-1.4.js"  />
    </FileGroup>
</root>

使用此代码:

var path = Server.MapPath("~/Scripts/ScriptfilesMashup.chirp.config");
var file = new XPathDocument(path);
var nav = file.CreateNavigator();
var nodes = nav.Select("/root/FileGroup/File");

但nodes 始终为空,无论我如何调用nav.Select 方法。我以前几乎没有使用过 XPath,所以也许我做错了——但是什么?只有选择器 * 给了我根节点。

获取所有File 节点的Path 属性的选择器是什么?

编辑:解决方案

感谢 Kirill,最终的解决方案如下所示:

var path = Server.MapPath("~/Scripts/ScriptfilesMashup.chirp.config");
var file = new XPathDocument(path);
var nav = file.CreateNavigator();
var ns = "urn:ChirpyConfig";

XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable);
nsMgr.AddNamespace("x", ns);

var nodes = nav.Select("/x:root/x:FileGroup/x:File/@Path", nsMgr);    
while(nodes.MoveNext())
{
    var path = nodes.Current.Value;
}

【问题讨论】:

  • 我过去也遇到过类似的问题,当时我忽略了一个事实,即涉及到一个 XML 命名空间。请参阅this answer 我的问题作为可能的提示。

标签: c# .net xml xpath xml-parsing


【解决方案1】:

这是因为 root、FileGroup 和 File 元素是在 urn:ChirpyConfig 命名空间中定义的。

使用这个:

XPathDocument xmldoc = new XPathDocument(xmlFile);
XPathNavigator nav = xmldoc.CreateNavigator();
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable);
nsMgr.AddNamespace("x", "urn:ChirpyConfig");
XPathNavigator result = nav.SelectSingleNode("/x:root/x:FileGroup/x:File", nsMgr);

【讨论】:

  • 非常感谢,我不知道它与命名空间有关。但是您的代码只给了我一个节点,但我需要字符串列表中的所有 Path 属性,我该怎么做?
  • @Marc,不客气。使用Select 而不是SelectSingleNode:msdn.microsoft.com/en-us/library/0ea193ac.aspx
  • 是的,我试过了,但我发现我必须将 XPath 更改为 /x:root/x:FileGroup/x:File/@Path。再次感谢,我将发布最终解决方案。
猜你喜欢
  • 1970-01-01
  • 2010-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多