2010-04-02 46 views
9

我將我的ASP.net MVC程序中的對象序列化爲xml字符串,如下所示;如何在c#中序列化對象時設置xmlns

StringWriter sw = new StringWriter(); 
XmlSerializer s = new XmlSerializer(typeof(mytype)); 
s.Serialize(sw, myData); 

現在,這給了我作爲前2行;

<?xml version="1.0" encoding="utf-16"?> 
<GetCustomerName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

我的問題是, 我如何可以改變的xmlns和編碼類型,序列化的時候?

感謝

回答

6

我發現作品是這行添加到我的課,

[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://myurl.com/api/v1.0", IsNullable = true)] 

,並加入到我的代碼添加命名空間,當我打電話,只要序列

XmlSerializerNamespaces ns1 = new XmlSerializerNamespaces(); 
    ns1.Add("", "http://myurl.com/api/v1.0"); 
    xs.Serialize(xmlTextWriter, FormData, ns1); 

爲兩個命名空間匹配它效果很好。

6

XmlSerializer類型在其構造函數的第二個參數是默認XML命名空間 - 在「的xmlns:」命名空間:

XmlSerializer s = new XmlSerializer(typeof(mytype), "http://yourdefault.com/"); 

設置編碼,我建議你使用XmlTextWriter代替直StringWriter,並創建它是這樣的:

XmlWriterSettings settings = new XmlWriterSettings(); 
settings.Encoding = Encoding.UTF8; 

XmlTextWriter xtw = XmlWriter.Create(filename, settings); 

s.Serialize(xtw, myData); 

XmlWriterSettings,您可以定義的選項過多 - 包括編碼。

相關問題