【问题标题】:Trying to convert xml to a dictionary试图将xml转换为字典
【发布时间】:2009-11-25 18:36:32
【问题描述】:

我的 xml 看起来像:

<root>
  <blah1>some text</blah1>
  <someother>blah aasdf</someother>
</root>

我想把它转换成字典

所以我可以这样做:

myDict["blah1"]

它返回文本“一些文本”

到目前为止我有:

Dictionary<string,string> myDict = (from elem in myXmlDoc.Element("Root").Elements()
                                select elem.Value).ToDictionary<string,string>();

这是正确的还是我必须将选择更改为具有 2 个结果的内容?

【问题讨论】:

    标签: c# xml linq dictionary


    【解决方案1】:

    指定您想要的 Key 和 Value。

    var myDict = myXmlDoc.Elements()
                         .ToDictionary( key => key.Name, val => val.Value);
    

    【讨论】:

      【解决方案2】:

      您需要在 ToDictionary 调用中使用一个 lambda,以便它知道键使用什么以及值使用什么...

      check here for a good example, and here as well

      【讨论】:

        【解决方案3】:
        myXmlDoc.Root
            .Elements()
            .ToDictionary(xe => xe.Name, xe => xe.Value);
        

        【讨论】:

          猜你喜欢
          • 2016-08-17
          • 1970-01-01
          • 2021-03-28
          • 1970-01-01
          • 2012-12-06
          • 2010-12-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多