views:

145

answers:

4

I am hoping someone has been through this pain ...

I have a XML

<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.

Any suggestion is appreciated..

A: 

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

mkato
A: 

You might have to implement ISerializable and change the root element in GetObjectData().

jrummell
+1  A: 

Did you try using the XmlAttributeOverrides class?

hjb417
You gotta just love all these goodies you find in the framework by surfing this site.
Matthew Whited
A: 

a sample of using XmlAttributeOverrides. If you vote up give one to hjb417 as well

class Program
{
    static void Main(string[] args)
    {
        using (var fs = File.OpenRead("XmlFile1.xml"))
        using (var fs2 = File.OpenRead("XmlFile2.xml"))
        {
            var xSer = new XmlSerializer(typeof(data));
            var obj = xSer.Deserialize(fs);
        //
            var xattribs = new XmlAttributes();
            var xroot = new XmlRootAttribute("dataNew");
            xattribs.XmlRoot = xroot;
            var xoverrides = new XmlAttributeOverrides();
            xoverrides.Add(typeof(data), xattribs);
            var xSer2 = new XmlSerializer(typeof(data), xoverrides);
            var obj2 = xSer2.Deserialize(fs2);
        }
    }
}

public class data
{
    public string elmt1 { get; set; }
    public string elmnt2 { get; set; }
    public string elmnt3 { get; set; }
}
Matthew Whited
Thanks Mathew but my challenge is to deserialize <data> to dataNew object. So, in your code the XML file will be the same but the serialization logic needs to perform something like belowvar xSer2 = new XmlSerializer(typeof(dataNew)); var obj2 = xSer2.Deserialize(fs1);
G33kKahuna
Mathew, any ideas ...thanks
G33kKahuna
In that case you would replace the XmlRootAttribute("dataNew") with "data" and the typeof(data) would be typeof(dataNew)
Matthew Whited