Groups | Blog | Home
all groups > dotnet xml > february 2006 >

dotnet xml : XmlXml() or XmlRaw() or XmlText(typeof(PCDATA)) or ??


junk NO[at]SPAM EveryBody-Fits.com
2/3/2006 4:35:07 AM
This seems something that should be easy and not uncommon... but hours
of searching have yielded nothing!

I am using XmlSerializer to map some XML (not defined by me) into some
class objects (defined by me). And it is working great for most cases.
Just have one more to handle...

One of the leaf nodes of the tree I build is "ci"... typically looks
like this:

<ci>someIdentifier</ci>

To implement that, my class "ci" has the following:

[XmlText(typeof(string))]
public string TheString = null;

Works great.

However, the XML allows for some presentation nodes inside <ci>. For
example:

<ci><msub><mi>T</mi><mn>0</mn></msub></ci> ==> gives you T with
subscript 0
<ci>&deg;C</ci> ==> gives you the typical way you'd write degrees
Celsius

To me, that presentation stuff is irrelevant. Its just a fancy
identifier. But I need to capture that string between the <ci> and the
</ci>, use it like I use "someIdentifier", and be able to serialize it
back out.

Unfortunately, that does NOT currently work... the XmlSerializer turns
the first case into a bunch of unrecognized nodes which vanish and
TheString ends up empty... and the XmlSerializer throws an exception on
the second case, because the entity "deg" is not known.

What I need is the ability to say "TheString holds all the raw XML
between <ci> and </ci>". So, something like:

[XmlXml()]
public string TheString = null;

[XmlRaw()]
public string TheString = null;

or perhaps to tell XmlText that the type of this thing is PCDATA:

[XmlText(typeof(PCDATA))]
public string TheString = null;

None of those are the answer; but I'm thinking the answer might be
similarly simple.

Suggestions?

Thanks.
junk NO[at]SPAM EveryBody-Fits.com
2/3/2006 4:07:03 PM
Finally figured it out... "ignore the MS documentation saying 'do not
do this'" ;^)

To override serialization behavior for a class, you can implement
IXmlSerializable and change from XmlType to XmlRoot. Pretty easy!

Then, to handle the raw text, you can do WriteRaw on the way out and
ReadInnerXml on the way in.

Just thought I'd document it for the next soul doing searches like I
was.
junk NO[at]SPAM EveryBody-Fits.com
2/3/2006 4:09:53 PM
Ooops, almost forgot...

For a better description of this and an example, go here:

http://weblogs.asp.net/cweyer/archive/2004/08/02/205798.aspx

and a thank you also to this page:

http://www.aspnetresources.com/blog/jumping_hoops_with_xml_serialization.aspx
AddThis Social Bookmark Button