InvalidOperationException on complex type SOAP serialization

I'm having a problem with serializing SOAP, and it would be great to find the answer. Here is a very simplified example:

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; } } 

If I run the Test () method, I get the following exception: System.InvalidOperationException: Token StartElement in state Epilog would result in an invalid XML document.

Would thank for any help.

+4
source share
2 answers

Use XmlWriter instead of StringWriter and create writer.WriteStartElement ("root");

This will work:

 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(); 
+3
source

Just note, the Top example will not work if the position of the stream is not set at the beginning of the stream. For instance:

 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()); s.Position = 0; StreamReader sr = new StreamReader(s); string data = sr.ReadToEnd(); 
+5
source

Source: https://habr.com/ru/post/1286403/


All Articles