c# - 如何将 XML 转换为字典

标签 c# xml linq linq-to-xml

我的 xml 如下:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <data name="LogIn">Log In</data>
  <data name="Password">Password</data>
</root>

我在没有 Linq 的情况下成功做到了这一点,任何人都可以帮助我将以下代码转换为 Linq:

using (XmlReader reader = XmlReader.Create(_xml))
{
    while (reader.Read())
    {
       if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "data")
       {
          reader.MoveToAttribute("name");
          string key = reader.Value;
          reader.MoveToContent();
          string value = reader.ReadElementContentAsString();
          _dictionary.Add(key, value);
       }
    }
    reader.Close();
}

最佳答案

var xdoc = XDocument.Load(path_to_xml);
_dictionary = xdoc.Descendants("data")
                  .ToDictionary(d => (string)d.Attribute("name"),
                                d => (string)d);

关于c# - 如何将 XML 转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13952425/

相关文章:

xml - 用于 Hudson 摄取的 Android InstrumentationTestRunner XML 输出

c# - XML 反序列化在 C# 中提供结构而非数据

c# - Linq 查询的复杂性限制

c# - 使用 LINQ 筛选嵌套集合并返回主对象

c# - 从 asp.net 中的网页生成 Pdf

c# - 无法从使用自定义运行时在 Docker 中运行 .NET Core 应用程序的 App Engine 连接到 Google Cloud SQL 中的 postgres

c# - WindowsFormsHost 上的工具栏覆盖

c# - ASP.NET 中的客户端系统时间

xml - grails/groovy和wslite-如何使静态XML动态化?

c# - 如何使用 Linq 和 C# 迭代从字典返回的列表