简体   繁体   English

从使用 xpath 的节点前缀的 xml 中提取对象

[英]Extracting objects from xml that uses node prefixes using xpath

I have the following XML in a file called C:\temp\config.xml:我在名为 C:\temp\config.xml 的文件中有以下 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.我现在正在尝试编写 C# 代码,该代码将从该 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.但是,此代码返回一个空的 xmlNodeList,因此最终循环没有项目。

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.我不知道如何使用 XmlNamespaceManager 来获取“dvp”前缀,或者当它从磁盘上的 XML 加载 XmlDocument 时是否能解决这个问题。

Can anyone give me some guidance how one goes about using xpath to retrieve values for xml with prefixed nodes?谁能给我一些指导如何使用 xpath 检索带有前缀节点的 xml 的值? 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.不幸的是,我没有能力更改 XML 的格式,所以我必须使用我提供的 xml。

thanks heaps,多谢,

David.大卫。

you can ignore the namespace using local-name()您可以使用 local-name() 忽略命名空间

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

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

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