简体   繁体   中英

Whats wrong with my XPath?

I try to parse this XML file (config file from 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. I barely used XPath before so maybe I'm doing it wrong - but what? Only the selector * gives me the root node.

What would be the selector to get the Path Attribute of all File nodes?

EDIT: SOLUTION

Thanks to Kirill, the final solution looks like this:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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