简体   繁体   中英

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?

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();

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;

If you use the Serialize overload (Stream, Object, XmlSerializerNamespaces) and provide null as XmlSerializerNamespaces the XmlSerializer won't attempt the failing WriteStartDocument. Try:

xs.Serialize(xw, obj, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM