16

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
orange
  • 720
  • 3
  • 11
  • 27

3 Answers3

24

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();
Jared Dykstra
  • 3,596
  • 1
  • 13
  • 25
Diego
  • 18,035
  • 5
  • 62
  • 66
  • 10
    Thank you, but I got this error: System.InvalidOperationException: WriteStartDocument cannot be called on writers created with ConformanceLevel.Fragment. – orange Feb 17 '12 at 17:22
  • 8
    @orange I had the same exception thrown, but setting `OmitXmlDeclaration = true` and explicitly setting `ConformanceLevel = ConformanceLevel.Auto` got me the expected result. – Grx70 Jan 20 '15 at 10:47
4

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;
dowhilefor
  • 10,971
  • 3
  • 28
  • 45
  • I've tried with `ConformanceLevel = ConformanceLevel.Fragment` but serialization fails. However `ConformanceLevel = ConformanceLevel.Auto` works like a charm (like it is written in the Diego's answer) – oleksa Oct 25 '17 at 08:32
1

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);
David Burg
  • 1,064
  • 12
  • 14
  • 1
    This also works. If you are custom serializing part of an object chain by implementing IXmlSerializable interface you already have a XmlWriter, so this solution becomes simpler. – NthDeveloper Apr 03 '17 at 11:19