XML Key值paire C#

san*_*alk 0 c# xml soap

这是我的XDocument

   <grantitem adnidtype="306" xmlns="http://tempuri.org/">
      <attribute key="AccountNumber" value="1111" />
      <attribute key="DateofMeterRead" value="20161226" />
      <attribute key="Arrears" value="11.11" />
      <attribute key="MeterRead" value="11111" />
    </grantitem>
Run Code Online (Sandbox Code Playgroud)

我试图通过使用来阅读这个

var q = from b in doc.Descendants("grantitem")
        select new
               {
                key= (string)b.Element("attribute key") ?? tring.Empty,
                value= (string)b.Element("value") ?? String.Empty
               };
Run Code Online (Sandbox Code Playgroud)

但是ist返回一个空值.有谁能看到一些失踪?

Jon*_*eet 5

这里有几个问题:

  • 您正在尝试获取名称grantitem中没有名称空间的元素,而您的元素实际上位于名称空间中http://tempuri.org/
  • 您正在尝试检索属性,就像它们是元素一样.您需要检索attribute子元素,grantitem然后检索这些元素的键/值属性

这是一个做你想要的例子:

using System;
using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        var doc = XDocument.Load("test.xml");
        XNamespace ns = "http://tempuri.org/";
        var query = doc
            .Descendants(ns + "grantitem")
            .Elements(ns + "attribute")
            .Select(x => new { 
                Key = (string) x.Attribute("key") ?? "",
                Value = (string) x.Attribute("value") ?? ""
            });

        foreach (var item in query)
        {
            Console.WriteLine(item);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以考虑使用创建KeyValuePair<string, string>值而不是使用匿名类型.

请注意,这是为了能够grantitem在doc中的任何位置找到多个元素.如果现实是总是有一个grantitem元素并且它始终是根元素,我可能会使用doc.Root.Elements(ns + "attribute")而不是Descendants先使用.