gpt4 book ai didi

c# - 复杂类型的 SOAP 序列化时出现 InvalidOperationException

转载 作者:太空狗 更新时间:2023-10-29 21:15:53 25 4
gpt4 key购买 nike

我遇到了 SOAP 序列化的问题,如果能找到答案就好了。这是一个非常简单的例子:

public void Test()
{
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);

SoapReflectionImporter importer = new SoapReflectionImporter();
XmlTypeMapping map = importer.ImportTypeMapping(typeof(A));
XmlSerializer serializer = new XmlSerializer(map);
serializer.Serialize(writer, new A());
}

[Serializable]
public class A
{
public A()
{
BB = new B();
}

public int a;

public B BB;
}
[Serializable]
public class B
{
public int A1 { get; set; }

public int A2 { get; set; }
}

如果我运行 Test() 方法,则会出现以下异常:System.InvalidOperationException: Token StartElement in state Epilog would result in an invalid XML document.

非常感谢任何帮助。

最佳答案

使用 XmlWriter 而不是 StringWriter 并执行 writer.WriteStartElement("root");

这会起作用:

Stream s = new MemoryStream();
XmlWriter writer = new XmlTextWriter(s, Encoding.UTF8);

SoapReflectionImporter importer = new SoapReflectionImporter();
XmlTypeMapping map = importer.ImportTypeMapping(typeof(A));
XmlSerializer serializer = new XmlSerializer(map);
writer.WriteStartElement("root");
serializer.Serialize(writer, new A());

StreamReader sr = new StreamReader(s);
string data = sr.ReadToEnd();

关于c# - 复杂类型的 SOAP 序列化时出现 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1011512/

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