Reputation: 1717
is it possible to partially (de)/serialize an object from/into a string?
class Foo
{
Bar Bar{get;set;}
string XmlJunkAsString{get;set;}
}
so ultmately, we would want the string below to work...
<Foo><Bar></Bar><XmlJunkAsString><xml><that/><will/><not/><be/><parsed/></xml></XmlJunkAsString></Foo>
and ultimately we could find the contents of Foo.XmlJunkAsString to contain the string
<xml><that/><will/><not/><be/><parsed/></xml>
and vice-versa would occur where the xml above would be generated when this particular instance of Foo is serialized.
possible?
Upvotes: 2
Views: 2234
Reputation: 1062660
I was hoping that [XmlText]
would work, but it seems to get escaped; you could implement IXmlSerializable
, but that is very tricky. The following is ugly, but gives the right result (although you might get some xml whitespace differences)
using System;
using System.ComponentModel;
using System.Xml;
using System.Xml.Serialization;
public class Bar { }
public class Foo
{
public Bar Bar { get; set; }
[XmlIgnore]
public string XmlJunkAsString { get; set; }
[XmlElement("XmlJunkAsString"), Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public XmlElement XmlJunkAsStringSerialized
{
get
{
string xml = XmlJunkAsString;
if (string.IsNullOrEmpty(xml)) return null;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
return doc.DocumentElement;
}
set
{
XmlJunkAsString = value == null ? null : value.OuterXml;
}
}
}
static class Program {
static void Main()
{
var obj = new Foo
{
Bar = new Bar(),
XmlJunkAsString = "<xml><that/><will/><not/><be/><parsed/></xml>"
};
var ser = new XmlSerializer(obj.GetType());
ser.Serialize(Console.Out, obj);
}
}
Upvotes: 2