迭代字符串XML以读取节点内部的内容

时间:2018-01-26 15:19:54

标签: c# xml

我有一个字符串的xml。这是其中的一部分。

    <GetModuleInfoResult xmlns =\"http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Results\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">
  <Code>0</Code>
  <Message i:nil=\"true\"/>
  <Parameters xmlns:a=\"http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Entities\">
    <a:Parameter>
      <a:Key>width</a:Key>
      <a:Value>1068</a:Value>
    </a:Parameter>
    <a:Parameter>
      <a:Key>height</a:Key>
      <a:Value>600</a:Value>
    </a:Parameter>

我想获取所有参数节点并阅读他们的&#39;键&#39;和&#39;价值&#39;节点

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

以下是从xml中获取键值对的一种方法

XDocument doc = XDocument.Load(/* YOUR XML FILE **/);
XNamespace x = "http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Entities";
var parameters = doc.Descendants(x + "Parameter").ToDictionary(e => e.Descendants(x + "Key").First().Value, e => e.Descendants(x + "Value").First().Value);