orange orange - 3 months ago 10
C# Question

How can I skip xml declaration when serializing?

I'm trying to output a xml file without xml head like
I tried:

Type t = obj.GetType();
XmlSerializer xs=new XmlSerializer(t);
XmlWriter xw = XmlWriter.Create(@"company.xml",
new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true });
xs.Serialize(xw,obj);
xw.Close();


But it's still outputing in the xml file.
I don't want string tricks. Any ideas?

Answer

Set the ConformanceLevel to Fragment, like this:

Type t = obj.GetType();
XmlSerializer xs=new XmlSerializer(t);
XmlWriter xw = XmlWriter.Create(@"company.xml",
                              new XmlWriterSettings() { 
                                   OmitXmlDeclaration = true
                                   , ConformanceLevel = ConformanceLevel.Auto
                                   , Indent = true });
xs.Serialize(xw,obj);
xw.Close();
Comments