2010-04-02 43 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,您可以定义的选项过多 - 包括编码。

相关问题