Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 925
orange Avatar asked Feb 17 '12 17:02

orange


2 Answers

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();
like image 52
Diego Avatar answered Oct 09 '22 04:10

Diego


Have a look in the documentation. There you see

The XML declaration is always written if ConformanceLevel is set to Document, even if OmitXmlDeclaration is set to true.

The XML declaration is never written if ConformanceLevel is set to Fragment. You can call WriteProcessingInstruction to explicitly write out an XML declaration.

So you need to add

ConformanceLevel = ConformanceLevel.Fragment;
like image 28
dowhilefor Avatar answered Oct 09 '22 02:10

dowhilefor