Xml标签编码错误

时间:2016-12-06 06:12:58

标签: c# xml encoding

我试图将对象列表写入有效的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();

不幸的是,写入文件时的输出如下所示:

&lt;People&gt;
  &lt;Person&gt;
    &lt;First&gt;Tom&lt;/First&gt;
    &lt;Last&gt;Hanks&lt;/Last&gt;
  &lt;/Person&gt;
&lt;/People&gt;
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);

我在这里做错了什么?

1 个答案:

答案 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;