SoapFormatter in .NET Core 3.1?



我应该如何将以下c#4.8框架迁移到。NET Core 3.1?

代码为:

public enum E { V }
[Serializable]
public class Person
{
public E my_enum;
public bool my_bool;
}
[...]
Person p = new Person();
using (FileStream fs = new FileStream("myfile.soap", FileMode.Create))
{
SoapFormatter f = new SoapFormatter();
f.Serialize(fs, p);
fs.Close();
}

给我预期的:

<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<a1:Person id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/ConsoleApp/ConsoleApp%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<my_enum>V</my_enum>
<my_bool>false</my_bool>
</a1:Person>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

读取后:

  • https://learn.microsoft.com/en-us/dotnet/standard/serialization/how-to-serialize-an-object-as-a-soap-encoded-xml-stream

和:

  • https://learn.microsoft.com/en-us/dotnet/standard/serialization/attributes-that-control-encoded-soap-serialization

以及:

  • https://github.com/dotnet/corefx/pull/15352

我试过了:

static void Main(string[] args)
{
Person p = new Person();
using (FileStream fs = new FileStream("myfile.soap", FileMode.Create))
{
XmlTypeMapping myTypeMapping = new SoapReflectionImporter()
.ImportTypeMapping(typeof(Person));
XmlSerializer mySerializer = new XmlSerializer(myTypeMapping);
mySerializer.Serialize(fs, p);
fs.Close();
}
}

这给了我:

<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1">
<my_enum xsi:type="E">V</my_enum>
<my_bool xsi:type="xsd:boolean">false</my_bool>
</Person>

这取决于您要修复的部分;如果是命名空间:告诉XmlSerializer它们

// note: this would be [XmlType(...)] if it wasn't the root element
[XmlRoot(Namespace = "http://schemas.microsoft.com/clr/nsassem/ConsoleApp/ConsoleApp%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull")]
public class Person
{
[XmlElement(Namespace = "")]
public E my_enum;
[XmlElement(Namespace = "")]
public bool my_bool;
}

如果是名称空间别名(尽管这不会改变含义(:

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("a1", "http://schemas.microsoft.com/clr/nsassem/ConsoleApp/ConsoleApp%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull");
XmlSerializer mySerializer = new XmlSerializer(typeof(Person));
mySerializer.Serialize(fs, p, ns);

如果是包装器节点:您将需要添加这些节点,也许通过类型,也许手动作为修复程序。

然而,从根本上讲,XmlSerializerSoapFormatter不是1:1可互换的,你不应该试图让它们互换。老实说,把它看作是一个基本的序列化开关,比试图破解它直到它有点工作更安全。

最新更新