How do I use XmlSerializer to insert an xml string

c#, serialization, xml

Solution

You can limit the custom serialization to just the element that needs special attention like so.

public class Root
{
    public string Name;

    [XmlIgnore]
    public string XmlString
    {
        get
        {
            if (SerializedXmlString == null)
                return "";
            return SerializedXmlString.Value;
        }
        set
        {
            if (SerializedXmlString == null)
                SerializedXmlString = new RawString();
            SerializedXmlString.Value = value;
        }
    }

    [XmlElement("XmlString")]
    [Browsable(false)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public RawString SerializedXmlString;
}

public class RawString : IXmlSerializable
{
    public string Value { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        this.Value = reader.ReadInnerXml();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteRaw(this.Value);
    }
}

Problem

I have defined the following class: ``` public class Root { public string Name; public string XmlString; } ``` and created an object: ``` Root t = new Root { Name = "Test", XmlString = "<Foo>bar</Foo>" }; ``` When I use XmlSerializer class to serialize this object, it will return the xml: ``` <Root> <Name>Test</Name> <XmlString>&lt;Foo&gt;bar&lt;/Foo&gt;</XmlString> </Root> ``` How do I make it not encode my XmlString content so that I can get the serialized xml as ``` <XmlString><Foo>bar</Foo></XmlString> ``` Thanks, Ian

Original source