如何使用XML Writer创建没有声明元素的XML

25

我正在使用XmlWriter.Create()来获取一个写入器实例,然后写入XML。但结果中包含了 <?xml version="1.0" encoding="utf-16" ?>,我该如何告诉我的xml写入器不要产生它?

3个回答

37

从您提供的文档中可以看到:“如果将ConformanceLevel设置为Document,则始终会编写XML声明,即使将OmitXmlDeclaration设置为true”。 - Cameron
大部分时间不是会设置为文档吗? - Cameron
@Cameron,我认为你自己回答了你的问题 :-) - Kirill Polishchuk
Kirill,抱歉我的无知,但是@Cameron是如何回答这个问题的? - ro͢binmckenzie
在至少 .NET Core 3.1 中,使用 ConformanceLevel.DefaultOmitXmlDeclaration = false 可以正常工作,并且不会写入 XML 声明头(当使用 XmlDocument.Save 时)。 - Dai
显示剩余3条评论

6

您可以创建 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的博客文章


谢谢,有更好的方法吗?我不想为了删除声明而子类化。 - ninithepug
@ninithepug:据我所知,没有。但是,如果您经常使用它,可以将其封装在静态方法中,这应该有助于保持代码整洁。 - Cameron
@ninithepug:看起来Kirill的答案(不需要新类)可能更好(除非你当然想要文档一致性级别)。 - Cameron

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接