开发者

Deserialize XML with different schemas into a shared type

Using c#, I want to deserialize xml from various sources into objects of a common type. The XML will not have the same schema. Eg, in the following xml, /thingContainer/thing/name and widget/@title both would map to myClass.DisplayName.

Xml1:

<thingContainer>
    <thing>
        <name>MyName&开发者_开发技巧lt;/name>
    </thing>
</thingContainer>

Xml2:

<widget title="myTitle" />

So, I can't mark up my class with [XmlElement], since it will be different depending on the source of my xml. Is there some trick I can do with inheritance or some helper class that will enable me to easily deserialize xml from different sources? Is there some easy way to map class fields to xpaths?

Of course, if I have to, I'll parse and manually deserialize the xml... but what fun is that?


Two thoughts that immediately spring to mind:

  • Use XSLT to transform the original XML into an interim format that matches your object model (a very popular approach, though personally I despise XSL)
  • Create interim object models to deserialize to, then map them to your final object model.

There's probably some XmlElement hackery possible, but it seems like it would be a messy approach.


I think you have two options here:

  1. Implement IXmlSerializable for your class and deserialize taking into account the structure of your XML
  2. Just use LINQ to XML to parse the XML and create an instance of your class. This is the approach I would pick (having gone through the first choice myself and not liking it)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜