我的XPath怎么了?
作者:互联网
<?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方法,节点始终为空.之前我几乎没有使用过XPath,所以也许我做错了-但是呢?只有选择器*给我根节点.
获取所有文件节点的路径属性的选择器是什么?
编辑:解决方案
感谢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;
}
解决方法:
这是因为元素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);
标签:xpath,xml,c,net,xml-parsing 来源: https://codeday.me/bug/20191031/1979096.html