I want to create custom xml serialization by implementing IXmlSerializable. I've got this test class that implements IXmlSerializable interface:
[Serializable]
public class Employee : IXmlSerializable
{
public Employee()
{
Name = "Vyacheslav";
Age = 23;
}
public string Name{get; set;}
public int Age { get; set; }
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
this.Name = reader["Name"].ToString();
this.Age = Int32.Parse(reader["Age"].ToString());
}
public void WriteXml(XmlWriter writer)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlWriter newWriter = XmlWriter.Create(writer, settings);
newWriter.WriteAttributeString("Name", this.Name);
newWriter.WriteAttributeString("Age", this.Age.ToString());
}
}
What I want to do is to omit xml declaration. For that I create proper instance of XmlWriterSettings and pass it as second parameter to create new XmlWriter. But when I debug this piece of code, I see that newWriter.Settings.OmitXmlDeclaration is set to false and serialized data contains tag. What am I doing wrong?
The actual serialization looks like this:
var me = new Employee();
XmlSerializer serializer = new XmlSerializer(typeof(Employee));
TextWriter writer = new StreamWriter(@"D:\file.txt");
serializer.Serialize(writer, me);
writer.Close();
And the second question is - if I want to serialize type Employee that has cutom type ContactInfo at field to be serialized, do I need to implement IXmlSerializable on ContactInfo too?
The writer-settings is a function of the outermost writer; you should be applying that to the code that creates the file, i.e.
additionally, then, you don't need to implement
IXmlSerializable
. You cannot do this at the inner level - it is too late.For example:
and if you don't want the extra namespaces, then:
which generates the file: