我的XPath有什么问题?

3

我试图解析这个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");

但是,无论我如何调用nav.Select方法,nodes始终为空。我之前几乎没有使用过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命名空间的存在。请参考这个答案作为可能的提示。 - Uwe Keim
1个回答

4

这是因为元素 rootFileGroupFile 在命名空间 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
@Marc,不用谢。使用Select代替SelectSingleNode:http://msdn.microsoft.com/en-us/library/0ea193ac.aspx - Kirill Polishchuk
是的,我尝试过了,但我发现我必须将XPath更改为/x:root/x:FileGroup/x:File/@Path。再次感谢,我会发布最终解决方案。 - Marc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接