how to create an xml using xml writer without declaration element

隐身守侯 提交于 2019-11-30 00:30:11

问题


I am using XmlWriter.Create() to get a writer instance then write the XML, but the result has the <?xml version="1.0" encoding="utf-16" ?>, how do I tell my xml writer do not produce it?


回答1:


Use XmlWriterSettings.OmitXmlDeclaration.

Don't forget to set XmlWriterSettings.ConformanceLevel to ConformanceLevel.Fragment.




回答2:


You can subclass XmlTextWriter and override the WriteStartDocument() method to do nothing:

public class XmlFragmentWriter : XmlTextWriter
{
    // Add whichever constructor(s) you need, e.g.:
    public XmlFragmentWriter(Stream stream, Encoding encoding) : base(stream, encoding)
    {
    }

    public override void WriteStartDocument()
    {
       // Do nothing (omit the declaration)
    }
}

Usage:

var stream = new MemoryStream();
var writer = new XmlFragmentWriter(stream, Encoding.UTF8);
// Use the writer ...

Reference: This blog post from Scott Hanselman.




回答3:


you can use XmlWriter.Create() with:

new XmlWriterSettings { 
    OmitXmlDeclaration = true, 
    ConformanceLevel = ConformanceLevel.Fragment 
}

    public static string FormatXml(string xml)
    {
        if (string.IsNullOrEmpty(xml))
            return string.Empty;

        try
        {
            XmlDocument document = new XmlDocument();
            document.LoadXml(xml);
            using (MemoryStream memoryStream = new MemoryStream())
            using (XmlWriter writer = XmlWriter.Create(
                memoryStream, 
                new XmlWriterSettings { 
                    Encoding = Encoding.Unicode, 
                    OmitXmlDeclaration = true, 
                    ConformanceLevel = ConformanceLevel.Fragment, 
                    Indent = true, 
                    NewLineOnAttributes = false }))
            {
                document.WriteContentTo(writer);
                writer.Flush();
                memoryStream.Flush();
                memoryStream.Position = 0;
                using (StreamReader streamReader = new StreamReader(memoryStream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }
        catch (XmlException ex)
        {
            return "Unformatted Xml version." + Environment.NewLine + ex.Message;
        }
        catch (Exception ex)
        {
            return "Unformatted Xml version." + Environment.NewLine + ex.Message;
        }
    }


来源:https://stackoverflow.com/questions/6833538/how-to-create-an-xml-using-xml-writer-without-declaration-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!