我试图将对象列表写入有效的xml。我的代码基本上看起来像这样:
public class Person
{
public string First { get; set; }
public string Last { get; set; }
}
List<Person> people = new List<Person>();
XElement elements = new XElement("People",
from p in people
select new XElement("Person",
new XElement("First", p.First),
new XElement("Last", p.Last)));
string output = elements.ToString();
不幸的是,写入文件时的输出如下所示:
<People> <Person> <First>Tom</First> <Last>Hanks</Last> </Person> </People>
XDeclaration declaration = new XDeclaration("1.0", "utf-8", "yes");
XProcessingInstruction procInstruction = new XProcessingInstruction("xml-stylesheet", "type='text/xsl'");
XElement root = new XElement("Store");
XDocument settingsFile = new XDocument(declaration, procInstruction, root);
foreach (string key in persistentSettings.Keys)
{
string value = persistentSettings[key];
if (!string.IsNullOrEmpty(value))
{
XElement setting = new XElement("Setting", new XAttribute("Name", key));
setting.Value = value;
root.Add(setting);
}
}
settingsFile.Save(SettingsFileName);
我在这里做错了什么?
答案 0 :(得分:0)
我必须在xElement
的构造函数中使用parse函数
XElement setting
= new XElement("Setting", new XAttribute("Name", key), XElement.Parse(value));
而不是
XElement setting = new XElement("Setting", new XAttribute("Name", key));
setting.Value = value;