Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

c# - How do I use XmlSerializer to insert an xml string

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...