tags:

views:

99

answers:

3

Hello StackOverflow!

i need help, i have some data coming in xml, i want to make an object out of, do something with it, serialize it back and send it away... but it must be some sort of custom serialization.

xml like:

<Animals Ver="12" class="1" something="2">
    <Dog Ver="12" class="2" something="17">
        <Name> a </Name>
        <Sound> oof </Sound>
        <SomeOtherProp>12</SomeOtherProp>

    </Dog>
    <Cat Ver="12" class="3" something="4">
       <Name> b </Name>
       <Sound> meow </Sound>
    </Cat>
</Animals>

needs to be presented as:

abstract class Animal :XmlMagic
{
  public string Name{get;set;}
  public string Sound{get;set;}

  public void SomeMagicalXMLSerializationMethod()
  {}
  public void SomeMagicalXMLDeSerializationMethod()
  {}
}

class Dog: Animal, XmlMagic
{
  public int SomeOtherProp{get;set;}
  public void SomeMagicalXMLSerializationMethod()
  {}
  public void SomeMagicalXMLDeSerializationMethod()
  {}
}
+2  A: 

The XmlMagic you are after is called IXmlSerializable interface: http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx

It provides you with 2 methods ReadXml and WriteXml, where you have to implement reading your object and writing it back. Then you use the standard .Net XmlSerializer to serialize/deserialize your objects.

Let me know if you need more help.

Grzenio
+2  A: 

However there are also XML Serialization Attributes like

[XmlAttribute]
[XmlArrayElement]
[XmlRoot]

etc, you can even use these attributes to control your serialization and acheive what you want without writing complicated serialization logic.

Akash Kava
A: 

You might want to check out the WCF REST Starter Kit; as it includes a visual studio add in called "Paste XML as Type"

Basically, you copy your raw XML, and then select that option; and it will generate a class for you based off that XML. Then you can do something simple like:

var xmlResponse = new XmlDocument();
xmlResponse.LoadXml(response);
var deserializedResponse = ConvertNode<ResponseWrapper.response>(xmlresponse); 

public static T ConvertNode<T>(XmlNode node) where T : class
        {
            var stm = new MemoryStream();

            var stw = new StreamWriter(stm);
            stw.Write(node.OuterXml);
            stw.Flush();

            stm.Position = 0;

            var ser = new XmlSerializer(typeof(T));
            var result = (ser.Deserialize(stm) as T);

            return result;
        }
Jim B