2013-02-12 19 views
13

Si consideri il seguente codice semplice che crea un documento XML e lo visualizza.Come ottenere XML con intestazione (<? Xml version = "1.0" ...)?

XmlDocument xml = new XmlDocument(); 
XmlElement root = xml.CreateElement("root"); 
xml.AppendChild(root); 
XmlComment comment = xml.CreateComment("Comment"); 
root.AppendChild(comment); 
textBox1.Text = xml.OuterXml; 

viene visualizzata, come previsto:

<root><!--Comment--></root> 

Non, però, visualizzare la

<?xml version="1.0" encoding="UTF-8"?> 

Così come posso ottenere che pure?

risposta

20

Crea un XML-dichiarazione con XmlDocument.CreateXmlDeclaration Method:

XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null); 
xml.AppendChild(docNode); 

Nota: si prega di dare un'occhiata alla documentazione per il metodo, in particolare per encoding parametro: ci sono requisiti particolari per i valori di questo parametro.

+0

Grazie. Pensavo fosse automatico. – ispiro

+0

+1. Si prega di notare che aspettarsi che "Utf-8" sia una mancata corrispondenza con la codifica della stringa (vedere +1 risposta Nicholas Carey). –

+0

@AlexeiLevenkov Grazie. Ma sono 'OuterXml'ing it e usando quello. O mi manca qualcosa e c'è un problema anche allora? – ispiro

10

È necessario utilizzare un XmlWriter (che scrive la dichiarazione XML di default). Dovresti notare che le stringhe C# sono UTF-16 e la tua dichiarazione XML dice che il documento è codificato UTF-8. Questa discrepanza può causare problemi. Ecco un esempio, scrivendo a un file che dà il risultato che ci si aspetta:

XmlDocument xml = new XmlDocument(); 
XmlElement root = xml.CreateElement("root"); 
xml.AppendChild(root); 
XmlComment comment = xml.CreateComment("Comment"); 
root.AppendChild(comment); 

XmlWriterSettings settings = new XmlWriterSettings 
{ 
    Encoding   = Encoding.UTF8, 
    ConformanceLevel = ConformanceLevel.Document, 
    OmitXmlDeclaration = false, 
    CloseOutput  = true, 
    Indent    = true, 
    IndentChars  = " ", 
    NewLineHandling = NewLineHandling.Replace 
}; 

using (StreamWriter sw = File.CreateText("output.xml")) 
using (XmlWriter writer = XmlWriter.Create(sw,settings)) 
{ 
    xml.WriteContentTo(writer); 
    writer.Close() ; 
} 

string document = File.ReadAllText("output.xml") ; 
4
XmlDeclaration xmldecl; 
xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null); 

XmlElement root = xmlDocument.DocumentElement; 
xmlDocument.InsertBefore(xmldecl, root); 
+1

Grazie. 'InsertBefore' sembra utile. – ispiro

Problemi correlati