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

后端 未结 2 663
[愿得一人]
[愿得一人] 2021-01-17 09:18

I have the following code:

class Program
{
    static void Main(string[] args)
    {
        using (var stream = File.Create(@\"C:\\test.xml\"))
        {
           


        
相关标签:
2条回答
  • 2021-01-17 10:23

    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);
    }
    
    0 讨论(0)
  • 2021-01-17 10:25

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

    0 讨论(0)
提交回复
热议问题