c#xml序列化
#region 序列化
/// <summary>
/// 序列化
/// </summary>
/// <param name="type">类型</param>
/// <param name="obj">对象</param>
/// <returns></returns>
public static string Serializer(Type type, object obj)
{
MemoryStream Stream = new MemoryStream();
XmlWriterSettings xws = new XmlWriterSettings();
xws.Indent = true;//是否缩进
xws.OmitXmlDeclaration = true;//是否包含报文头<?xml version="1.0" encoding="UTF-8"?>
xws.Encoding = Encoding.GetEncoding("UTF-8");//编码格式
XmlWriter xtw = XmlTextWriter.Create(Stream, xws);
XmlSerializer xml = new XmlSerializer(type);
//省略去掉XML命名空间及声明头
XmlSerializerNamespaces _namespaces = new XmlSerializerNamespaces(
new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "aa")
});
try
{
//序列化对象
// xml.Serialize(Stream, obj);
xml.Serialize(xtw, obj, _namespaces);
}
catch (InvalidOperationException)
{
throw;
}
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
string str = sr.ReadToEnd();
sr.Dispose();
Stream.Dispose();
return str;
}
#endregion
第一个问题:编码格式
不知道为什么对方认为我的编码方式就是不对,从对方对接的接口中返回的编码格式是EUC_CN,一查是GB2312的一种,对方系统用的php,据说是下面的代码实现的:`
$encode = mb_detect_encoding($string, array("ASCII",'UTF-8′,"GB2312′,"GBK",'BIG5′));
并没有解决将格式转换为UTF-8的问题,通过测试,对方终于获得了他们要的格式,代码如下:`
public static string newSerializer(Type type, object obj)
{
if (obj == null) return null;
XmlSerializer serializer = new XmlSerializer(type);
MemoryStream stream = new MemoryStream();
XmlTextWriter xtw = new XmlTextWriter(stream,null);//编码格式
// xtw.Formatting = Formatting.Indented;//自动缩进
//省略去掉XML命名空间及声明头
XmlSerializerNamespaces _namespaces = new XmlSerializerNamespaces(
new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "aa")
});
try
{
serializer.Serialize(xtw, obj, _namespaces);
}
catch { return null; }
stream.Position = 0;
string returnStr = string.Empty;
//读出到string
using (StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("GB2312")))
{
string line = "";
while ((line = sr.ReadLine()) != null)
{
returnStr += line;
}
}
转化为UTF8
//UTF8Encoding utf8 = new UTF8Encoding();
//Byte[] encodedBytes = utf8.GetBytes(returnStr);
return returnStr;
}
xml序列化,不进行初始化,默认是UTF8,输入输出流按照GB2312的编码,对方获得了UTF8的编码。
第二个问题:回调接口
对方传入的xml序列化,我获取到的是对方除了传输的数据,还有很多别的标头:
------------------------------bd6f1df02c8d
Content-Disposition: form-data; name=“xml”
<?xml version="1.0" encoding="UTF-8"?>use_info<2020-04-24 12:39:05------------------------------bd6f1df02c8d–
获取代码如下:
//获取回调的xml参数
string Notify = "";
byte[] bytes = context.Request.BinaryRead(context.Request.ContentLength);
Notify = System.Text.Encoding.UTF8.GetString(bytes);
这个时候进行xml反序列化时,会提示:根级别上的数据无效。
本来项找一个可以直接获取到xml的方式,没找到,只好分割字符串了。
string strtemp = "\n";
string contextNotify = Regex.Split(Notify, strtemp, RegexOptions.IgnoreCase)[3]; ;