简体   繁体   中英

Extracting objects from xml that uses node prefixes using xpath

I have the following XML in a file called C:\temp\config.xml:

<?xml version="1.0" encoding="utf-8"?>
<dvp:systemConfig xmlns:devop="urn:foo.com:sys:rules">
    <dvp:map id="rootFolderMap">
        <dvp:entry key="anything" value="folder1"/>
        <dvp:entry key="config" value="folder2"/>
        <dvp:defaultValue value="folder1" />
    </dvp:map>
    <dvp:map id="folderMappings">
        <dvp:entry key="SYS" value="System" />
        <dvp:entry key="OPS" value="Operations" />
        <dvp:entry key="DEV" value="Development" />
        <dvp:defaultValue value="Miscellaneous" />
    </dvp:map>

</dvp:systemConfig>

I am now trying to write C# code that will extract values from this XML. In particular, the list of value properties in the nodes.

List<string> folderNames = new List<string>
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\temp\config.xml");
XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);

XmlNodeList xmlNodeList =
    doc.SelectNodes("/systemConfig/map[@id='folderMappings']/entry",nsMgr);
foreach (XmlNode xmlNode in xmlNodeList)
{        
    // I'm hoping xmlNodeList now contains a list of <dvp:entry> nodes.
    string folderName = xmlNode.Attributes["value"].ToString().Trim(); 
    folderNames.Add(folderName);
}

However, this code returns an empty xmlNodeList, so the final loop has no items.

I'm not sure how to use the XmlNamespaceManager to pick up the "dvp" prefix, or whether it figures this out when it loads the XmlDocument from the XML on disk.

Can anyone give me some guidance how one goes about using xpath to retrieve values for xml with prefixed nodes? Unfortunately I do not have the power to change the format of the XML so I have to work with the xml I'm provided with.

thanks heaps,

David.

you can ignore the namespace using local-name()

XmlNodeList xmlNodeList =
    doc.SelectNodes("/*[local-name()='systemConfig']/*[local-name()='map'][@id='folderMappings']");

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