从Dictionary生成XML

Atu*_*eka 0 c# xml dictionary linq-to-xml

我有一个带键值对的字典.我想用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")
        )
    )
);
Run Code Online (Sandbox Code Playgroud)

Mal*_*ger 5

如果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))))
);
Run Code Online (Sandbox Code Playgroud)