gpt4 book ai didi

c# - XmlSerializer - 不支持编码

转载 作者:行者123 更新时间:2023-11-30 21:19:06 26 4
gpt4 key购买 nike

我有以下扩展方法来序列化我的类....

        public static string SerializeToXml<T>(this object obj)
{
XDocument doc = new XDocument();

XmlSerializer ser = new XmlSerializer(typeof(T));

using (var writer = doc.CreateWriter())
{
ser.Serialize(writer, obj);
}

return doc.ToString();

}

这似乎工作正常并为我的序列化对象返回以下字符串:

<AuthenticatedUser xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Username>mark</Username>
<UserID>4</UserID>
<Roles>
<string>AuthenticatedUsers</string>
</Roles>
<IsValid>false</IsValid>
</AuthenticatedUser>

然而,当我尝试使用下面的方法反序列化这个字符串时,我得到了这个错误:

{"The encoding style '<AuthenticatedUser xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n  <Username>mark</Username>\r\n  <UserID>4</UserID>\r\n  <Roles>\r\n    <string>AuthenticatedUsers</string>\r\n  </Roles>\r\n  <IsMale>false</IsMale>\r\n</AuthenticatedUser>' is not valid for this call because this XmlSerializer instance does not support encoding. Use the SoapReflectionImporter to initialize an XmlSerializer that supports encoding."}

方法....

 public static T DeserializeFromXml<T>(this string xml)
{
var element = XElement.Parse(xml);

XmlSerializer ser = new XmlSerializer(typeof(T));

using (var reader = element.CreateReader())
{
return (T)ser.Deserialize(reader, xml);
}
}

所以在阅读错误消息后,我更改了反序列化方法以使用 SoadReflectionImporter....

 public static T DeserializeFromXml<T>(this string xml)
{
var element = XElement.Parse(xml);

SoapReflectionImporter soap = new SoapReflectionImporter();
var mapping = soap.ImportTypeMapping(typeof(T));
XmlSerializer ser = new XmlSerializer(mapping);

using (var reader = element.CreateReader())
{
return (T)ser.Deserialize(reader, xml);
}
}

但是我现在得到这个错误...

{"The encoding style '<AuthenticatedUser xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n  <Username>mark</Username>\r\n  <UserID>4</UserID>\r\n  <Roles>\r\n    <string>AuthenticatedUsers</string>\r\n  </Roles>\r\n  <IsValid>false</IsValid>\r\n</AuthenticatedUser>' is not valid for this call. Valid values are 'http://schemas.xmlsoap.org/soap/encoding/' for SOAP 1.1 encoding or 'http://www.w3.org/2003/05/soap-encoding' for SOAP 1.2 encoding."}

有谁知道我哪里出错了以及如何成功反序列化这个字符串?

最佳答案

问题是您正在调用的 Deserialize 方法的重载:

            return (T)ser.Deserialize(reader, xml);

调用中的 xml 参数指定编码样式,但在这种情况下,您将传递来自序列化的 xml。简单地删除第二个参数并用阅读器调用反序列化,它应该可以正常工作:

            return (T)ser.Deserialize(reader);

关于c# - XmlSerializer - 不支持编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3953175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com