I want to use XmlSerializer to serialize a class, typical stuff. My ONE difference is I want to serialize a custom object "ComplexType" as as attribute, not a child element.
I've seen other stack overflow questions and the answers say it's not possible. I know that's wrong.
The error is like:
"XmlAttribute/XmlText can not be used to encode complex types."
--or--
"XmlAttribute/XmlText can not be used to encode types implementing IXmlSerializable."
Simply change myfield from ComplexType to DateTime and it works fine. DateTime is definitely complex, so I just need to know what to change in the class or attributes.
ex: YES
<Container myComplexType="specialencoding" />
ex: NO
<Container>
<myComplexType>specialencoding</myComplexType>
</Container>
-- See how much nicer the first one is... I want that one.
-- Code is like this...
[XmlRoot(ElementName="Container")]
public class Container
{
[XmlAttribute(AttributeName="myComplexType")]
public ComplexType myfield = new ComplexType();
}
public class ComplexType
{
public ComplexType(){}
public ComplexType(string encoding){}
public override string ToString() {return "specialencoding";}
}
If I implement ComplexType : IXmlSerializable, I get the second error message above.
Basic serializer used:
XmlSerializer serializer = new XmlSerializer(typeof(Container));
serializer.serialize("outfile.xml", new Container());