问题描述
使用下面的代码序列化XmlSerializer对象
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
代码:
private static bool StudentsReport(string filePath,Students std)
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedname.Empty });
XmlSerializer serializer = new XmlSerializer(typeof(Students));
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,OmitXmlDeclaration = true,};
using (XmlWriter writer = XmlWriter.Create(filePath,settings))
{
serializer.Serialize(writer,std,namespaces );
}
return true;
}
学生类别为:
public class Students
{
private string studentID;
private string studentName;
/// <summary>
/// To store Machine Details.
/// </summary>
public string ID
{
get { return this.studentID; }
set { this.studentID = value; }
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Name
{
get { return this.studentName; }
set { this.studentName = value; }
}
}
解决方法
使用standalone
方法添加WriteStartDocument
值。
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,//OmitXmlDeclaration = true,// must be false
};
using (XmlWriter writer = XmlWriter.Create(filePath,settings))
{
writer.WriteStartDocument(standalone: true);
serializer.Serialize(writer,std,namespaces);
}
一些提示。
将Students
类重命名为Student
。因为它描述的是一个学生,而不是一个学生。
ID
属性重命名为Id
。参见Naming Guidelines
更改方法签名:void StudentReport
。总是返回相同的bool值是没有意义的。