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