2011-07-26 30 views

Respuesta

21

Use XmlWriterSettings.OmitXmlDeclaration.

No olvides establecer XmlWriterSettings.ConformanceLevel en ConformanceLevel.Fragment.

+0

A partir de los documentos con los que enlace: 'La declaración XML se escribe siempre si ConformanceLevel se establece en el Documento, incluso si OmitXmlDeclaration se establece en TRUE – Cameron

+0

@Cameron, True y? –

+0

¿No estará configurado para Documentar la mayor parte del tiempo? – Cameron

4

Usted puede subclase XmlTextWriter y reemplazar el método WriteStartDocument() no hacer nada:

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

Uso:

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

Referencia: Esta blog post de Scott Hanselman.

+0

gracias, ¿alguna forma mejor? No quiero hacer una subclase solo para eliminar la declaración. – ninithepug

+0

@ninithepug: No tan lejos como sé, lo siento. Sin embargo, puedes envolverlo en un método estático en algún lado si lo usas a menudo. Eso debería ayudar a mantenerlo limpio – Cameron

+0

gracias, agradezco – ninithepug

2

puede utilizar con 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; 
     } 
    } 
Cuestiones relacionadas