Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change root element name while keeping contents using XmlSerializer?

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?

like image 275
G33kKahuna Avatar asked Sep 21 '09 20:09

G33kKahuna


2 Answers

If it's only the root name you want to change you can specify the root attribute when declaring the XmlSerializer.

XmlSerializer xmlSerializer = new XmlSerializer(typeof(data), new XmlRootAttribute("dataNew"));
like image 53
Aaron Avatar answered Sep 27 '22 22:09

Aaron


XmlRootAttribute was supposed to work

[XmlRoot("dataNew")]
public class MyData()
{
    [XmlElement("elmt1")]
    public string myElement1{get;set;}

    [XmlElement("elmnt2")]
    public string myElement2{get;set;}

    [XmlElement("elmtn3")]
    public string myElement3{get;set;}

}

EDIT: Completed the XML

like image 31
mkato Avatar answered Sep 27 '22 21:09

mkato