XmlTypeMapping myTypeMapping = new SoapReflectionImporter().ImportTypeMapping(typeof(AddressValidationRequest));
XmlSerializer serializer = new XmlSerializer(myTypeMapping);
TextWriter writer = new StreamWriter(filename);
serializer.Serialize(writer, request);
writer.Close();
I am trying to serialize a class into XML (SOAP). I keep receiving the error message below. Does anyone know why this might be happening?
System.InvalidOperationException: 'There was an error generating the XML document.'
InvalidOperationException: Token StartElement in state Epilog would result in an invalid XML document.
System.InvalidOperationException
HResult=0x80131509
Message=There was an error generating the XML document.
Source=System.Private.Xml
StackTrace:
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
This exception was originally thrown at this call stack:
System.Xml.XmlTextWriter.AutoComplete(System.Xml.XmlTextWriter.Token)
System.Xml.XmlTextWriter.WriteStartElement(string, string, string)
System.Xml.Serialization.XmlSerializationWriter.WriteStartElement(string, string, object, bool, System.Xml.Serialization.XmlSerializerNamespaces)
System.Xml.Serialization.XmlSerializationWriter.WriteArray(string, string, object, System.Type)
System.Xml.Serialization.XmlSerializationWriter.WriteReferencedElement(string, string, object, System.Type)
System.Xml.Serialization.XmlSerializationWriter.WriteReferencedElements()
System.Xml.Serialization.ReflectionXmlSerializationWriter.GenerateTypeElement(object, System.Xml.Serialization.XmlTypeMapping)
System.Xml.Serialization.ReflectionXmlSerializationWriter.WriteObject(object)
System.Xml.Serialization.XmlSerializer.SerializeUsingReflection(System.Xml.XmlWriter, object, System.Xml.Serialization.XmlSerializerNamespaces, string, string)
System.Xml.Serialization.XmlSerializer.Serialize(System.Xml.XmlWriter, object, System.Xml.Serialization.XmlSerializerNamespaces, string, string)
Inner Exception 1:
InvalidOperationException: Token StartElement in state Epilog would result in an invalid XML document.
CodePudding user response:
Use XmlTextWriter
instead of TextWriter
and do a writer.WriteStartElement("wrapper")
:
XmlTypeMapping myTypeMapping = new SoapReflectionImporter().ImportTypeMapping(typeof(AddressValidationRequest));
XmlSerializer serializer = new XmlSerializer(myTypeMapping);
XmlTextWriter writer = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
writer.Formatting = System.Xml.Formatting.Indented;
writer.WriteStartElement("wrapper");
serializer.Serialize(writer, request);
writer.WriteEndElement();
writer.Close();
Reference: