所以基本上我有2门课:
public class Configuration
{
public Configuration()
{
Sections = new List<Section>();
}
public List<Section> Sections { get; private set; }
}
public class Section : IXmlSerializable
{
public string Name { get; set; }
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
Name = reader.GetAttribute("Name");
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("Name", Name);
}
}
此代码运行良好:
var configuration = new Configuration();
configuration.Sections.Add(new Section {Name = "#Submitter.LoginTest"});
configuration.Sections.Add(new Section {Name = "Default"});
using (StreamWriter writer = new StreamWriter(@"d:\data.xml"))
{
XmlSerializer x = new XmlSerializer(typeof(Configuration));
x.Serialize(writer, configuration, XmlSerializerHelper.EmptyNamespaces);
}
序列化结果:
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Sections>
<Section Name="#Submitter.LoginTest" />
<Section Name="Default" />
</Sections>
</Configuration>
但是此代码引发异常:System.Xml.dll 中发生类型为“System.InvalidOperationException”的未处理异常附加信息:XML 文档中存在错误 (4、6)。
var configuration = new Configuration();
using (StreamReader reader = new StreamReader(@"d:\data.xml"))
{
XmlSerializer x = new XmlSerializer(typeof(Configuration));
configuration = (Configuration) x.Deserialize(reader);
}
所以对于部分的序列化我不能使用基于属性的序列化,但它工作得很好:
public class Section
{
[XmlAttribute]
public string Name { get; set; }
}
UPD1:Section 作为 root 的序列化/反序列化效果很好