Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
254 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...