如何解决我想获取标头为<?xml version = \“ 1.0 \” encoding = \“ UTF-8 \” Standalone = \“ yes \”?>的XML
使用下面的代码序列化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值是没有意义的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。