Class is serialized to XML without a class name
I try to serialize a class, defined as following:
[DataContract]
public class Human
{
public Human() { }
public Human(int id, string Name, bool isEducated)
{
this.i开发者_开发知识库d = 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; }
}
Then it's being serialized:
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);
And this is the outcome:
<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>
Not something I'd expect. Class name is just omited. What is the problem here?
You are explicitly naming the root element "Repository", which is why it is showing up that way. Try omitting that statement :)
I think what you want is to have Human after this Repository element. To do that, you will need to make another root element below the Repository one and then serialize your object into that. You should note that the XmlSerializer is typically used to write objects to xml files, not really create entire xml files. I have an example of something that might work for you below:
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();
Something like that...I'm really sleepy :/
精彩评论