简体   繁体   English

我的XPath有什么问题?

[英]Whats wrong with my XPath?

I try to parse this XML file (config file from Chirpy ): 我尝试解析这个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>

with this code: 使用此代码:

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

but nodes is always empty, regardless of how I call the nav.Select method. 但无论我如何调用nav.Select方法, nodes始终为空。 I barely used XPath before so maybe I'm doing it wrong - but what? 我之前几乎没有使用XPath,所以也许我做错了 - 但是什么? Only the selector * gives me the root node. 只有选择器*给我根节点。

What would be the selector to get the Path Attribute of all File nodes? 获取所有File节点的Path属性的选择器是什么?

EDIT: SOLUTION 编辑:解决方案

Thanks to Kirill, the final solution looks like this: 感谢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;
}

It is because elements root , FileGroup and File are defined in urn:ChirpyConfig namespace. 这是因为元件rootFileGroupFile中定义urn:ChirpyConfig命名空间。

Use this: 用这个:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM