2

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?

Vikrant
  • 4,920
  • 17
  • 48
  • 72
superlazyname
  • 265
  • 3
  • 7
  • 17
  • 2
    Don't use XmlTextWriter at all. Use XmlWriter.Create to create a new XmlWriter instance. – John Saunders Jun 27 '10 at 20:49
  • 1
    `XmlTextWriter` is a "left-over" from V1.0/1.1, which has been functionally replaced by the variants created by `XmlWriter.Create()`. Note that this does return writers which are slightly different in behavior compared to the `XmlTextWriter`, but this is not usually a problem. – Lucero Jun 27 '10 at 21:03

3 Answers3

4

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).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

The XML declaration is this:

<?xml version="1.0" encoding="utf-8"?>

It should be on top of every XML document because it informs the parser about the encoding used (and the XML version, but that is not important as of today).

Lucero
  • 59,176
  • 9
  • 122
  • 152
0

So

writer = XmlWriter.Create("file path");

has the same effect as

XmlTextWriter writer = new XmlTextWriter("file path", type);

correct?

Answered, you guys are fast!

Would there be any reason to use Xmltextwriter, or is it just out of date? I'm only asking because I saw a lot of sources using XmlTextWriter and XmlTextReader.

superlazyname
  • 265
  • 3
  • 7
  • 17
  • 2
    It is quite out of date. Expecially you have to be careful with the `XmlTextReader` since it does load the DTD as well (even though it doesn't use it, it does load and check it for well-formedness, which can cause you trouble for instance with W3C DTDs). I had a web page loading and processing an XHTML document, and it ended up throwing exceptions due to W3C returning 503 errors... see here: http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic – Lucero Jun 27 '10 at 21:10