2
XDocument xdoc = new XDocument(
        new XDeclaration("1.0", null, null),
        new XElement(bla));

using (var writer = new XmlTextWriter(@"folderpath\index.xml", new UTF8Encoding(false)))
{
    //writer.Formatting = Formatting.Indented;
    xdoc.Save(writer);
}

I have to generate an XML document which matches exactly my sample. This code however produces:

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

but it should look like this:

<?xml version="1.0"?>

How can I solve this either with XMLTextWriter or linq?

poke
  • 369,085
  • 72
  • 557
  • 602
Sebastian
  • 66
  • 1
  • 6
  • For `XmlTextWriter`, at least, there's [the `OmitXmlDeclaration` option](https://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.omitxmldeclaration(v=vs.110).aspx). You can then manually write the version part of the declaration manually before saving the document. Not sure if there's a nicer solution, this seems like a bit of a hack. – Cameron Jul 13 '15 at 17:52
  • You shouldn't really be using `XmlTextWriter` directly. Per [the docs](https://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.xmltextwriter(v=vs.110).aspx) you should be using `XmlWriter.Create` instead. – Charles Mager Jul 13 '15 at 18:12

1 Answers1

4

See the documentation.

If encoding is null it writes the file out as UTF-8, and omits the encoding attribute from the ProcessingInstruction.

Use:

using (var writer = new XmlTextWriter(@"folderpath\index.xml", null))

Also, see the source code for XmlTextWriter.

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
  • 2
    Why was this downvoted? This seems to work just fine. And UTF-8 should be the default file encoding anyway, so omitting the encoding shouldn’t cause any problems. – poke Jul 13 '15 at 19:58