[.net] Deserialize XML Text Element to Custom Object

Started by
0 comments, last by Nypyren 13 years, 1 month ago
The XML serialization/deserialization framework included in .NET will automatically deserialize the text contents of an element into most fundamental types (bool, int, string, etc.), but I'm wondering if there's a way to extend that so that I could turn an element like this:

<Vector>0, 0, 0</Vector>

into a custom Vector object, for example. I've read through a lot of the documentation and found how to deserialize complex objects with child elements, but I haven't seen a way to parse the inner text differently as I would need to for the above. The only way I know to do that currently is deserialize it as a string and manually parse it after the fact for each Vector element, or to do this:

<Vector>
<X>0</X>
<Y>0</Y>
<Z>0</Z>
</Vector>

I know I need to write the code to split it up and parse the values, I'm just wondering if I can set it up so that it automatically happens if a Vector object is being deserialized.

Anyone know about this? Thanks!
Advertisement
You can use a read/write property to do this: http://codethatworks...zed-attributes/

Make a string property, have its 'get' portion construct the comma-separated-string from the X,Y,Z fields. Then make the 'set' property take an input string and parse it out into the X,Y,Z fields. Then add the XmlIgnore attribute to the X,Y,Z fields so that they get skipped individually during (de)serialization.

The (de)serializer will operate on the property, which will automatically compose/decompose your X,Y,Z parts.

This topic is closed to new replies.

Advertisement