2010-09-21 65 views
0
 XmlDocument doc = new XmlDocument(); 
     doc.AppendChild(doc.CreateElement("Foo")); 
     doc.DocumentElement.InnerXml = "Test";  
     StringBuilder result = new StringBuilder(); 
     doc.WriteContentTo(XmlWriter.Create(result)); 

在結束時,結果是:爲XmlDocument的設定InnerXml導致缺失結束標籤

<Foo>Test 

,這意味着端部元件缺失。爲什麼是這樣的,我該如何解決它?

回答

6

問題是你正在創建一個XmlWriter,但沒有處理它 - 所以它不是沖洗。試試這個:

using System; 
using System.Text; 
using System.Xml; 

class Test 
{ 
    static void Main() 
    { 
     XmlDocument doc = new XmlDocument(); 
     doc.AppendChild(doc.CreateElement("Foo")); 
     doc.DocumentElement.InnerXml = "Test";  
     StringBuilder result = new StringBuilder(); 
     using (XmlWriter writer = XmlWriter.Create(result)) 
     { 
      doc.WriteContentTo(writer); 
     } 
     Console.WriteLine(result); 
    } 
} 

輸出:

<?xml version="1.0" encoding="utf-16"?><Foo>Test</Foo>