1

I want to know the reason behind the XmlWriter.WriteStartDocument() and XmlWriter.WriteEndDocument().

In my scenario I am creating an XML document with some data in it, e.g:

XmlWriter xmlWriter = XmlWriter.Create(file);

xmlWriter.WriteStartDocument();

// write xml elements and attributes...

xmlWriter.WriteEndDocument();

xmlWriter.Flush();

While serializing, XmlWriter does not throw any exception if we skip the call to xmlWriter.WriteStartDocument() and just call xmlWriter.WriteEndDocument() at the end.

The below code snippet does not throw any error or exception:

XmlWriter xmlWriter = XmlWriter.Create(file);

// write xml elements and attributes...

xmlWriter.WriteEndDocument();

xmlWriter.Flush();

How is this possible? And can you explain the functionality of WriteStartDocument() and WriteEndDocument()?

Charles Mager
  • 25,735
  • 2
  • 35
  • 45
Arun Prasad
  • 360
  • 3
  • 18
  • @stuartd But in C#, it is working fine with the WriteEndDocument() alone. – Arun Prasad Nov 28 '16 at 10:52
  • @stuartd My questions is "why both the statements aren't necessary for writing the xml declaration into the file ?". Just "WriteEndDocument()" alone is enough to write the xml declaration. It seems to be odd. – Arun Prasad Nov 28 '16 at 11:00
  • @stuartd in XML 1.0 (which is what's most commonly used, 1.1 is very rare), [the declaration is optional](http://stackoverflow.com/questions/7007427/does-a-valid-xml-file-require-an-xml-declaration). – Charles Mager Nov 28 '16 at 18:22

1 Answers1

3

Per the documentation for WriteStartDocument, this method writes the XML declaration which appears before the root element::

When overridden in a derived class, writes the XML declaration.

And per the documentation for WriteEndDocument:

When overridden in a derived class, closes any open elements or attributes and puts the writer back in the Start state.

There is no mention that either is related to or dependent on the other, and indeed your experiments seem to prove this.

Unlike other similarly named method pairs like WriteStartElement and WriteEndElement, calling one of these without the other cannot get you into a state where the document is invalid. That said, I would still advise you should call them at the start and end of writing a document, as this is evidently what the API intends you to do.

As an aside, it's rare to need to use XmlReader and XmlWriter directly like this. They are very low level XML APIs. I'd suggest you explore LINQ to XML and XmlSerializer for most use cases.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45