【问题标题】:Loop through a specific node of XML with XmlNodeList使用 XmlNodeList 循环遍历 XML 的特定节点
【发布时间】:2014-09-28 04:19:34
【问题描述】:

我有以下 XML 类型文件

<root>
<info version_id=... product_id=... account_id=...>
<CRM>
<result key=... value=...>
<result key=... value=...>
....
</CRM>
<result key=... value=....>
</info>

<info version_id=... product_id=... account_id=...>
<CRM>
<result key=... value=...>
<result key=... value=...>
....
</CRM>
<result key=... value=....>
</info>
</root>

我需要为每个“信息”节点创建以下列表: 列表(帐户+产品、密钥、值) 而且我必须只获取属于 CRM 节点的“关键”和“价值”信息。

所以我想要的就是这段代码

string[] directoryXml = Directory.GetFiles(directory);
var listxmlresult = new List<XmlResultNode>();

foreach (var xmlfile in directoryXml)
{
    var docxml = new XmlDocument();
    docxml.Load(xmlfile);
    XmlNodeList nodesInfo = docxml.SelectNodes("//info");
    XmlNodeList nodesResult = docxml.SelectNodes("//info/CRM/result");


    foreach (XmlNode info in nodesInfo)
    {

        string VersionId = info.Attributes["version_id"].Value;
        string ProductId = info.Attributes["product_id"].Value;
        string AccountId = info.Attributes["account_id"].Value;
        string AccountProductId = AccountId + " : " + ProductId;


        // verify that CRM node exist

        if (docxml.SelectSingleNode("//info/CRM") == null)
        {
            //To do log info that CRM node is not available for the specific file
        }

        foreach (XmlNode result in nodesResult)
        {
            //To do verfiy value is empty

            string Key = result.Attributes["key"].Value;
            string Value = result.Attributes["value"].Value;

            if (Value.Length != 0)
            {
                var listXmlResultTemp = new XmlResultNode(AccountProductId, Key, Value);
                listxmlresult.Add(listXmlResultTemp);
            }
        }
    }
}

但此代码返回列表,其中包含每个“accountproduct”的所有“key”“value”。

我无法在第二个循环中仅读取当前节点。 我尝试了几种 xpath 可能性,但我无法使用 XmlNodeList 获取当前位置。

Tks

【问题讨论】:

    标签: c# xml xmldocument xmlnodelist


    【解决方案1】:

    您在发布时想要达到的目标不是很清楚。我认为您想以这种方式更改内部循环:

    foreach (XmlNode result in info.SelectNodes("./CRM/result"))
    {
        string Key = result.Attributes["key"].Value;
        string Value = result.Attributes["value"].Value;
        .....
        .....
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      相关资源
      最近更新 更多