我尝试序列化一个类,定义如下:
[DataContract]
public class Human
{
public Human() { }
public Human(int id, string Name, bool isEducated)
{
this.id = id;
this.Name = Name;
this.isEducated = isEducated;
}
[DataMember]
public int id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public bool isEducated { get; set; }
}
然后它被序列化了:
Human h = new Human(id, Name, isEducated);
XmlRootAttribute root = new XmlRootAttribute();
root.ElementName = "Repository";
XmlSerializer xs = new XmlSerializer(typeof(Human), root);
FileStream fs = new FileStream(fname, FileMode.Open);
xs.Serialize(fs, h);
这就是结果:
<Repository xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<id>1</id>
<Name>Vill</Name>
<isEducated>false</isEducated>
</Repository>
不是我所期待的。类名称只是省略。这有什么问题?
答案 0 :(得分:3)
您明确地命名了根元素“Repository”,这就是它以这种方式显示的原因。尝试省略该陈述:)
我认为你想要的是在这个Repository元素之后拥有Human。为此,您需要在Repository下面创建另一个根元素,然后将对象序列化为该元素。您应该注意,XmlSerializer通常用于将对象写入xml文件,而不是真正创建整个xml文件。我有一个可能对你有用的例子:
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(FilePath, null);
writer.WriteStartDocument();
writer.Formatting = Formatting.Indented;
writer.WriteStartElement("Repository");
Human h = new Human(id, Name, isEducated);
XmlRootAttribute root = new XmlRootAttribute();
root.ElementName = "Human";
XmlSerializer xs = new XmlSerializer(typeof(Human), root);
xs.Serialize(writer, h);
writer.WriteEndElement();
writer.Close();
那样的东西......我真的很困倦:/