2013-02-12 33 views
13

請考慮以下簡單的代碼,它可以創建一個XML文檔並將其顯示出來。如何使用標題獲取XML(<?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; 

它顯示,符合市場預期:

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

這不,但是,顯示

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

所以,我怎麼能拿到呢?

回答

20

創建使用XmlDocument.CreateXmlDeclaration Method一個XML聲明:

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

注:請看一看該方法的文檔,尤其encoding參數:有這個參數的值的特殊要求。

+0

感謝。我認爲這是自動的。 – ispiro 2013-02-12 18:53:34

+0

+1。請注意,預計「Utf-8」與字符串編碼不匹配(請參閱+1 Nicholas Carey答案)。 – 2013-02-12 19:59:55

+0

@AlexeiLevenkov謝謝。但是我用'OuterXml'來使用它。或者我錯過了一些東西,甚至有問題? – ispiro 2013-02-12 21:40:11

10

您需要使用XmlWriter(默認情況下會寫入XML聲明)。你應該注意到,C#字符串是UTF-16,你的XML聲明說這個文檔是UTF-8編碼的。這種差異可能會導致問題。下面是一個例子,寫,讓你期望的結果的文件:

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

謝謝。 'InsertBefore'看起來很有用。 – ispiro 2013-12-18 14:50:09

相關問題