2011-07-26 17 views

Odpowiedz

21

Użyj XmlWriterSettings.OmitXmlDeclaration.

Nie zapomnij ustawić XmlWriterSettings.ConformanceLevel na ConformanceLevel.Fragment.

+0

Od docs Ci link do niego: 'Deklaracja XML jest zawsze napisany jeśli ConformanceLevel jest ustawiony na dokument, nawet jeśli OmitXmlDeclaration jest ustawiony na TRUE – Cameron

+0

@Cameron, prawdziwy , i? –

+0

Czy nie będzie ustawiona na Dokumentowanie przez większość czasu? – Cameron

4

Można podklasy XmlTextWriter i zastąpić metodę WriteStartDocument() robić nic:

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

Zastosowanie:

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

referencyjny: Ten blog post Scott Hanselman.

+0

dzięki, w jakikolwiek lepszy sposób? Nie chcę podklasy tylko w celu usunięcia deklaracji. – ninithepug

+0

@ninithepug: Nie z tego, co wiem, przepraszam. Możesz go zawinąć w statyczną metodę gdzieś, jeśli używasz jej często. To powinno pomóc w utrzymaniu czystości. – Cameron

+0

dziękuje człowiekowi, doceniam to: – ninithepug

2

można użyć XmlWriter.Create() z:

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; 
     } 
    } 
Powiązane problemy