I have an XML document:
<data>
<elmt1>Element 1</elmt1>
<elmnt2>Element 2</elmnt2>
<elmnt3>Element 3</elmnt3>
</data>
I need to deserialize to an object that serializes to a different root name with everything else remaining the same.
For example:
<dataNew>
<elmt1>Element 1</elmt1>
<elmnt2>Element 2</elmnt2>
<elmnt3>Element 3</elmnt3>
</dataNew>
When serializing, we can always apply XmlRootAttribute
to serialize to a different root name but I am not sure how to deserialize to a different XmlRootAttribute
. It keeps failing error in document (1,2)
pointing to the root attribute.
How can I achieve that?
If it's only the root name you want to change you can specify the root attribute when declaring the XmlSerializer.
XmlRootAttribute was supposed to work
EDIT: Completed the XML
a sample of using XmlAttributeOverrides. If you vote up give one to hjb417 as well
You can use ExtendedXmlSerializer. This serializer support change root element name and property name. If you have class like this:
You can serialize it:
Your xml will look like:
ExtendedXmlSerializer has many other useful features:
ExtendedXmlSerializer supports .net 4.5 and .net Core. You can integrate it with WebApi and AspCore.
Did you try using the XmlAttributeOverrides class?
You might have to implement ISerializable and change the root element in GetObjectData().