Reputation: 1
This is my first attempt at serializing an XML and I need to understand why errors occur in my code:
private void function(Object2 InputParameters)
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer s = new XmlSerializer(typeof(Object1));
StringWriter XMLWriter = new StringWriter();
s.Serialize(XMLWriter, InputParameters, ns);
XmlDocument DOC_Xml = new XmlDocument();
DOC_Xml.LoadXml(XMLWriter.ToString());
}
InnerException:
{"An object of type 'SRV.Entities.Object2' cannot be converted to type 'SRV.Entities.Object1'."}
StackTrace:
" in System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)\r\n in System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)\r\n "
The error line is at s.Serialize(XMLWriter, ParametrosEntrada, ns);
but I don't understand the reason.
How could I solve the serialization between different objects?
Thank you, guys.
Upvotes: 0
Views: 73
Reputation: 27852
You have a bug
private void function(Object2 InputParameters)
and
XmlSerializer s = new XmlSerializer(typeof(Object1));
you need
XmlSerializer s = new XmlSerializer(typeof(Object2));
aka, you need to consistently have "Object2" as the input parameter AND the argument of "typeof".
More deeply, you can consider Generics. So you can pass the type is.... as needed . Either Object1 OR Object2. (but not both)
private void MyFunction<T>(T InputParameters)
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer s = new XmlSerializer(typeof(T));
StringWriter XMLWriter = new StringWriter();
s.Serialize(XMLWriter, InputParameters, ns);
XmlDocument DOC_Xml = new XmlDocument();
DOC_Xml.LoadXml(XMLWriter.ToString());
}
You can see more at this SOF answer:
Using generics with XmlSerializer
Upvotes: 1