Search code examples
c#documentxmltextwritersystem.xml

System.Xml.XmlTextWriter.WriteStartDocument()


What does this method do, and why is it necessary?

The "go to definition" option leads me to a function containing all comments, here's what it says about its purpose

//Writes the XML declaration with the version "1.0" and the standalone attribute.

what does it mean by writes the XML declaration?
Is this when it creates the .xml file?

How does it relate to the constructor XmlTextWriter()'s purpose?


Solution

  • To start with, it belongs to XmlWriter, not really XmlTextWriter. As John Saunders says, the preferred way of creating an XmlWriter is via XmlWriter.Create.

    The point of WriteStartDocument is to create this in the output stream:

    <?xml version="1.0" ?>
    

    This isn't written when you just create the XmlWriter. It will also potentially specify the encoding. (XML defaults to UTF-8 or UTF-16 if an encoding isn't specified.)

    As for whether you need it - XML documents don't have to have an XML declaration, but they "should" according to the spec (i.e. it's best practice).