如何使用没有声明元素的xml编写器创建xml

问题描述 投票:16回答:3

我使用XmlWriter.Create()获取一个编写器实例然后编写XML,但结果有<?xml version="1.0" encoding="utf-16" ?>,我怎么告诉我的xml编写器不生成它?

c# .net xml xmlwriter
3个回答
29
投票

使用XmlWriterSettings.OmitXmlDeclaration

别忘了将XmlWriterSettings.ConformanceLevel设置为ConformanceLevel.Fragment


5
投票

你可以继承XmlTextWriter并覆盖WriteStartDocument()方法什么都不做:

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

用法:

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

参考:这是来自Scott Hanselman的blog post


2
投票

你可以使用XmlWriter.Create()

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;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.