Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my XDocument saving the declaration when I don't want it to?

I have the following code:

class Program
{
    static void Main(string[] args)
    {
        using (var stream = File.Create(@"C:\test.xml"))
        {
            var xml =
                new XElement("root",
                    new XElement("subelement1", "1"),
                    new XElement("subelement2", "2"));

            var doc = new XDocument(xml);
            doc.Declaration = null;
            doc.Save(stream);
        }
    }
}

I am trying to get XML to save without the xml declaration, but even though I am nulling out the declaration of the XDocument, it is still being saved to the final XML.

This code is outputting:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <subelement1>1</subelement1>
  <subelement2>2</subelement2>
</root>
like image 551
KallDrexx Avatar asked Jan 19 '12 13:01

KallDrexx


1 Answers

Instead XDocument.Save() you can use XmlWriter with XmlWriterSettings.OmitXmlDeclaration set to true

using System.IO;
using System.Xml;
using System.Xml.Linq;

XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Indent = true;

using (var stream = File.Create(@"C:\test.xml"))
using (XmlWriter xw = XmlWriter.Create(stream, xws))
{
    var xml = new XElement(
        "root",
        new XElement("subelement1", "1"),
        new XElement("subelement2", "2"));

    xml.Save(xw);
}
like image 153
sll Avatar answered Sep 28 '22 01:09

sll