views:

128

answers:

1

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?

+1  A: 

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);
    }
}
Marc Gravell
Good answer. I have a modification that I think will make it better..change XmlJunkAsStringSerialized get function to pad the loaded xml with a junk 'root' element. perhaps doc.LoadXml('<XmlJunkAsStringSerializedRoot>' + xml + '</XmlJunkAsStringSerializedRoot>');and change the setter function to return value.InnerXml;this way you can have xml that is not contained in a root element.
E Rolnicki