23

XmlWriter.Create()ライターインスタンスを取得してからXMLを書き込むために使用していますが、結果にはが含まれ<?xml version="1.0" encoding="utf-16" ?>ています。xmlライターがそれを生成しないようにするにはどうすればよいですか?

4

3 に答える 3

33

を使用しXmlWriterSettings.OmitXmlDeclarationます。

XmlWriterSettings.ConformanceLevelに設定することを忘れないでくださいConformanceLevel.Fragment

于 2011-07-26T16:48:43.260 に答える
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 ...

参照:ScottHanselmanによるこのブログ投稿。

于 2011-07-26T16:49:40.077 に答える
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;
        }
    }
于 2016-02-03T23:40:23.233 に答える