Alex Rivera | Logout

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

Asked 2012-01-19T13:26:09.743
17

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>
Edit
Report

1 Answer

9

You can do this using XmlWriter with a custom XmlWriterSettings (you'll need a using directive for System.Xml):

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

class Program
{
    static void Main(string[] args)
    {
        var xml =
            new XElement("root",
                         new XElement("subelement1", "1"),
                         new XElement("subelement2", "2"));

        var doc = new XDocument(xml);
        var settings = new XmlWriterSettings
        {
            OmitXmlDeclaration = true
        };
        using (var stream = File.Create(@"test.xml"))
        {
            using (var writer = XmlWriter.Create(stream, settings))
            {
                doc.Save(writer);
            }
        }
    }
}

That's assuming you want to specify the Stream - you can also create an XmlWriter from the filename:

using (var writer = XmlWriter.Create("test.xml", settings))
{
    doc.Save(writer);
}

(If you don't need the XDocument for anything else, you can just call Save on the root element, of course, in the same way.)

answered 2012-01-19T13:38:43.907

Your Answer