Sunday, 21 September 2014

Deserializing alternative XML element names in Silverlight



I have a Silverlight application which uses .NET XmlSerializer to deserialize objects from simple typeless namespaceless XML hierarchical data received from the network. A simplified example how it currently works:



[XmlType(AnonymousType = true)]
[XmlRoot("entity", Namespace = "", IsNullable = false)]
public class Entity
{
[XmlArray(ElementName = "children", Form = XmlSchemaForm.Unqualified, IsNullable = false)]
[XmlArrayItem("entity")]
public List<Entity> Children { get; set; }

[XmlAttribute("id")]
public string Id { get; set; }
}


The XML is as follows:



<entity id="1">
<children>
<entity id="2">
<children>
<entity id="3">
</entity>
<entity id="4">
</entity>
</children>
</entity>
</children>
</entity>


Now the server side has changed to provide alternative XML with shorter element names to save network bandwidth. The new XML format is as follows:



<e i="1">
<c>
<e i="2">
<c>
<e i="3">
</e>
<e i="4">
</e>
</c>
</e>
</c>
</e>


The problem is that I cannot just change the Xml attributes to match the new XML version, I need to support both old and new formats on my Silverlight application.


The first idea to make my Entity class universal was like this:



[XmlType(AnonymousType = true)]
[XmlRoot("entity", Namespace = "", IsNullable = false)]
[XmlRoot("e", Namespace = "", IsNullable = false)]
public class Entity
{
[XmlArray(ElementName = "children", Form = XmlSchemaForm.Unqualified, IsNullable = false)]
[XmlArrayItem("entity")]
[XmlArray(ElementName = "c", Form = XmlSchemaForm.Unqualified, IsNullable = false)]
[XmlArrayItem("e")]
public List<Entity> Children { get; set; }

[XmlAttribute("id")]
[XmlAttribute("i")]
public string Id { get; set; }
}


but I got an error because multiple XmlRoot and XmlArray and XmlArrayItem attributes are not allowed.


Is there any way I can make XmlSerializer to be able to deserialize my current Entity class from both kinds of XML without any changes in the other code which is using Entity class?


If .NET XmlSerializer is not able to do that, is there any Silverlight compatible alternative which supports multiple choices for element names?


No comments:

Post a Comment