2011-07-26 60 views

回答

21

使用XmlWriterSettings.OmitXmlDeclaration

不要忘記將XmlWriterSettings.ConformanceLevel設置爲ConformanceLevel.Fragment

+0

從您鏈接到文檔:'如果ConformanceLevel設置爲文件,即使OmitXmlDeclaration設置爲TRUE; – Cameron

+0

@Cameron XML聲明總是寫的,真和? –

+0

大部分時間不會設置爲文檔嗎? – Cameron

4

你也可以繼承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 ... 

參考:這blog post斯科特Hanselman的。

+0

謝謝,有什麼更好的辦法?我不想爲了刪除聲明而繼承子類。 – ninithepug

+0

@ninithepug:據我所知,不好意思。不過,如果你經常使用它,你可以將它包裝在某個靜態方法中。這應該有助於保持它的清潔 – Cameron

+0

謝謝你,欣賞它 – ninithepug

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