使用 LIST 数据生成 XML 文件

Generate XML File using the LIST Data

我有如下列表中的数据。

List<APIConfigValue> 

现在我必须生成 XML 文件,如下所示。

    <?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="ScanTime.Web" value="11D_SVC1" />
    <add key="eTime.Punch" value="true" />
    <add key="DataMartUrl" value="syscontrol" />
  </appSettings>
</configuration>

根据列表中的记录数,应该会自动生成。 我正在尝试使用 xml linq 库。

我就是这样开始的...

XDocument doc = new XDocument(
            new XElement("configuration",
                new XElement("appSettings",
                    new XElement("add", new XAttribute("key", "APP.Web"), new XAttribute("value", "true"))
                    )
            )
        );

我卡住了如何从这里的列表循环。我试图找到文章。但没有什么接近。 感谢您的宝贵时间和回复。

假设您已相应地填充列表:

List<APIConfigValue> yourList = //assign your list here;
foreach (APIConfigValue apiConfigItem in yourList)
{
    //write out your nodes from the list here using apiConfigItem
}

我假设每个 APIConfigValue 都有两个属性:keyvalue

List<APIConfigValue> data = foo;
XDocument doc = new XDocument(
    new XElement("configuration",
        new XElement("appSettings",
            data.Select((conf) => new XElement("add", new XAttribute("key", conf.key), new XAttribute("value", conf.value)).ToArray()
        )
    )
);

这样做是将每个 APIConfigValue 映射到具有两个属性的 XElementAPIConfigValuekeyvalue

但是,如果您计划同时导出和导入这种 XML 格式,我建议您查看 XMLSerializer class.