从字典生成XML

本文关键字:XML 字典 | 更新日期: 2023-09-27 18:18:18

我有一个键值对的字典。我想用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")
        )
    )
);

从字典生成XML

如果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))))
);

假设您有一个Country类和一个Id和一个Name,并且国家作为值存储在您的字典国家中,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)));

这家伙拿着字典

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