2012-12-28 77 views
1

我有,看起來像..添加XML聲明字符串XML

<Root> 
<Data>Nack</Data> 
<Data>Nelly</Data> 
</Root> 

我想補充"<?xml version=\"1.0\"?>"這個字符串的一些XML數據。然後將xml保存爲一個字符串。

我嘗試了一些東西..

這種斷裂,失去原有的XML字符串

myOriginalXml="<?xml version=\"1.0\"?>" + myOriginalXml; 

,這並不做任何事,只是保持原始的XML數據,不附加任何聲明。

XmlDocument doc = new XmlDocument(); 
       doc.LoadXml(myOriginalXml); 
       XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8","no"); 
       StringWriter sw = new StringWriter(); 
       XmlTextWriter tx = new XmlTextWriter(sw); 
       doc.WriteTo(tx); 
       string xmlString = sw.ToString(); 

這也似乎不會有任何效果..

XmlDocument doc = new XmlDocument(); 
       doc.LoadXml(myOriginalXml); 
       XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "no"); 
       MemoryStream xmlStream = new MemoryStream(); 
       doc.Save(xmlStream); 
       xmlStream.Flush(); 
       xmlStream.Position = 0; 
       doc.Load(xmlStream); 
       StringWriter sw = new StringWriter(); 
       XmlTextWriter tx = new XmlTextWriter(sw); 
       doc.WriteTo(tx); 
       string xmlString = sw.ToString(); 
+0

的可能重複[我的XDeclaration?](http://stackoverflow.com/questions/6269881/where-is-my-xdeclaration) –

+0

也許我的代碼是錯誤的,但保存文件不工作 –

回答

3

使用一個xmlwritersettings達到節省上更大的控制權。該XmlWriter.Create接受設置(而不是默認的構造器)

var myOriginalXml = @"<Root> 
          <Data>Nack</Data> 
          <Data>Nelly</Data> 
          </Root>"; 
    var doc = new XmlDocument(); 
    doc.LoadXml(myOriginalXml); 
    var ms = new MemoryStream(); 
    var tx = XmlWriter.Create(ms, 
       new XmlWriterSettings { 
          OmitXmlDeclaration = false, 
          ConformanceLevel= ConformanceLevel.Document, 
          Encoding = UTF8Encoding.UTF8 }); 
    doc.Save(tx); 
    var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray()); 
+0

編碼是utf-16我需要utf-8是一個簡單的修復這個代碼? –

+0

我加了這個..Encoding = System.Text.Encoding.UTF8,但編碼仍然是utf-16 –

+0

+1。 @NickLaMarca - 檢查建議的重複 - 它包含你需要的所有信息(你需要編碼器,你想要的編碼,'StringWriter'顯然是UTF-16)。 –