partial xml serialization/deserialization

2019-05-26 17:51发布

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条回答
地球回转人心会变
2楼-- · 2019-05-26 18:49

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);
    }
}
查看更多
登录 后发表回答