【问题标题】:Generate XML from Dictionary从字典生成 XML
【发布时间】:2013-06-14 11:16:11
【问题描述】:

我有一本带有键值对的字典。我想使用 LINQ 将其写入 XML。

我能够使用 LINQ 创建 XML 文档,但不确定如何从字典中读取值并将其写入 XML。

以下是使用硬编码值生成 XML 的示例,我想准备字典而不是硬编码值

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "true"),
    new XElement("countrylist",
        new XElement("country",
            new XAttribute("id", "EMP001"),
            new XAttribute("name", "EMP001")
        ),
        new XElement("country",
            new XAttribute("id", "EMP001"),
            new XAttribute("name", "EMP001")
        )
    )
);

【问题讨论】:

  • Dictionary 的定义是什么?

标签: c# xml dictionary linq-to-xml


【解决方案1】:

如果id属性存储为字典键,名称存储为值,可以使用如下

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "true"),
    new XElement("countrylist",
        dict.Select(d => new XElement("country",
            new XAttribute("id", d.Key),
            new XAttribute("name", d.Value))))
);

【讨论】:

  • 不错!但是, doc.ToString() 没有声明就返回。你知道如何从 doc(包括声明)返回完整的 xml 字符串吗?
【解决方案2】:

假设您有一个 Country 类,其中包含一个 Id 和一个 Name,并且国家/地区作为值存储在您的字典 countries 中,其中 id 是键:

XDocument xDoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"));
var xCountryList = new XElement("countrylist");
foreach(var kvp in countries)
    xCountryList.Add(new XElement("country",
        new XAttribute("id", kvp.Key),
        new XAttribute("name", kvp.Value.Name)));

【讨论】:

    【解决方案3】:

    这里有字典的老兄

            Dictionary<int, string> fooDictionary = new Dictionary<int, string>();
            fooDictionary.Add(1, "foo");
            fooDictionary.Add(2, "bar");
    
            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-8", "true"),
                new XElement("countrylist")
            );
    
            var countryList = doc.Descendants("countrylist").Single(); // Get Country List Element
    
            foreach (var bar in fooDictionary) {
                // Add values per item
                countryList.Add(new XElement("country",
                                    new XAttribute("id", bar.Key),
                                    new XAttribute("name", bar.Value)));
            }
    

    【讨论】:

      猜你喜欢
      • 2014-10-04
      • 2013-02-06
      • 2021-01-23
      • 1970-01-01
      • 2020-05-25
      • 2014-05-17
      • 2013-07-02
      • 2010-11-24
      • 1970-01-01
      相关资源
      最近更新 更多