views:

368

answers:

3

I have a very specific deserialization need, see example below:

say I have following class:

[Serializable]
public class Person {
public string Name { get; set; }
public string PersonXml { get; set; }
}

and following XML

<Person>
  <Name>John</Name>
  <PersonXml><someXmlFragment>text</someXmlFragment></PersonXml>
</Person>

What I want is the XmlSerializer class to deserialize InnerXml of the <PersonXml> element to the PersonXml property as a string. I'm wondering if it can be done.

NOTE: I know I can encode the content of <PersonXml> escaping illegal XML chars, but I would prefer to leave the inner XML more human friendly (not containing &lt; and other entities that will only cofuse my end user)

+1  A: 

So, even though the element actually contains XML elements, you want .NET to pretend it is really a string? I don't think this is possible through standard serialization.

However, you could load the XML, transform the PersonXml and properly escape it and then replace the contents of the PersonXml with the newly escaped data. It would involve manually manipulating the XML before deserializing it, but then you could keep the XML elements under the PersonXml.

Ryan
Yeah, but this seems to me like too much hassle and a pretty ugly solution :)
Piotr Owsiak
+1  A: 

You can always implement IXmlSerializable and do whatever you fancy through XmlReader.

Anton Tykhyy
Right, I did not consider such path.This would definitely solve my problem, although I was hoping for some cheaper solution :)Thanks!
Piotr Owsiak
BTW, you don't need [Serializable] for XML serialization. [XmlElemenht("Name")] can be omitted too, since in this particular case it does not change XMLSerializer's default behaviour.
Anton Tykhyy
A: 

Why not use XML to represent XML? Just use XmlElement for PersonXml.

It's always a bad idea to pretend that XML is the same thing as String.

John Saunders