Custom XML Serialization

I need help, I have data coming in xml, I want to make an object from it, do something with it, serialize it and send it ... but it should be some kind of ordinary 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> 

should 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() {} } 
+4
c # xml
source share
3 answers

XmlMagic , after which the IXmlSerializable interface is called: http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx

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

Let me know if you need more help.

+7
source share

However, there are also XML Serialization attributes, such as

 [XmlAttribute] [XmlArrayElement] [XmlRoot] 

etc., you can even use these attributes to control serialization and achieve what you want without writing complex serialization logic.

+4
source share

You might want to check out the WCF REST starter kit; since it includes the visual studio add in the title "Insert XML as Type"

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

 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; } 
0
source share

All Articles