2014-05-06 125 views
0

我想創建一個xml文檔並將其保存在字符串對象中。將xml文檔轉換爲編碼爲utf-8的字符串

我指的SO這兩個問題,保存和編碼目的

我的代碼:

StringBuilder builder = new StringBuilder(); 

XDocument doc = new XDocument(new XElement("BANKID", 
     new XElement("ReqID", "WEB"), 
     new XElement("ReqHeader", "CASHDEP"), 
     new XElement("CurrencyCode", ""), 
     new XElement("CurrencyAbbrivation", ""))); 

using (TextWriter writer = new Utf8StringWriter(builder)) // Error Line 
{ 
doc.Save(writer); 
} 
builder.ToString(); 

public class Utf8StringWriter : StringWriter 
{ 
    public override Encoding Encoding { get { return Encoding.UTF8; } }   
} 

它給了我錯誤說「 Utf8StringWriter不包含需要的構造函數1 arguments「

如何修改那個接受參數爲StringBuilder的類?

+0

類似:[計算器Q](http://stackoverflow.com/questions/3871738/force-的XDocument到寫入到字符串與 - UTF-8編碼)? – Aidanapword

回答

1

您的自定義Utf8StringWriter類沒有構造函數接受參數,但您嘗試將值傳遞給它。這就是爲什麼你會收到錯誤信息。

添加一個接受StringBuilder的公共構造,然後將它傳遞給基類:

public class Utf8StringWriter : StringWriter 
{ 
    public Utf8StringWriter(StringBuilder stringBuilder) 
     :base(stringBuilder) 
    { 
    } 

    public override Encoding Encoding { get { return Encoding.UTF8; } } 
}