Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidOperationException while SOAP serialization of complex type

I encountered a problem with SOAP serialization and it would be great to find an answer. Here's 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 method Test() then I get the following exception: System.InvalidOperationException: Token StartElement in state Epilog would result in an invalid XML document.

Would appreciate any help.

like image 922
Dmitrii Lobanov Avatar asked Jun 18 '09 08:06

Dmitrii Lobanov


2 Answers

Use XmlWriter instead of StringWriter and do a 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();
like image 155
SO User Avatar answered Sep 22 '22 06:09

SO User


Just a note, The upper example will not work if the position of the stream is not set to the start of the stream. Like so:

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();
like image 27
Gregor Slavec Avatar answered Sep 18 '22 06:09

Gregor Slavec