【问题标题】:XML Key value paire C#XML 键值对 C#
【发布时间】:2018-06-18 11:19:46
【问题描述】:

这是我的 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>

我正在尝试使用

阅读此内容
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
               };

但是 ist 返回一个空值。任何人都可以看到缺少的东西吗?

【问题讨论】:

    标签: c# xml soap


    【解决方案1】:

    这里有几个问题:

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

    这是一个你想做的例子:

    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);
            }
        }
    }
    

    您可以考虑使用创建 KeyValuePair&lt;string, string&gt; 值而不是使用匿名类型。

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

    【讨论】:

    • 你可以直接去attribute而不是grantitem
    • @DavidG:仅当 OP 在同一命名空间中没有任何其他名为 attribute 的元素时。如果文档只是这个,我可能会选择doc.Root.Elements(ns + "attribute")。但是,鉴于原始查询的结构,它最终可能会成为更大文档的一部分。我会在答案中添加一些类似的内容。
    【解决方案2】:

    我喜欢用字典来做这个:

    Dictionary<string,string> dict = from b in doc.Descendants("grantitem").FirstOrDefault().Elements("attribute").GroupBy(x => (string)x.Attribute("key"), y => (string)y.Attribute("value"))
       .ToDictionary(x => x.Key, y => y.FirstOrDefault());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      相关资源
      最近更新 更多