Serialize XML with XML string

旧时模样 提交于 2021-01-21 07:43:48

问题


I have to produce the following XML

<object>
    <stuff>
        <body>
            <random>This could be any rondom piece of unknown xml</random>
        </body>
    </stuff>
</object>

I have mapped this to a class, with a body property of type string.

If I set the body to the string value: "<random>This could be any rondom piece of unknown xml</random>"

The string gets encoded during serialization. How can I not encode the string so that it gets written as raw XML?

I will also want to be able to deserialize this.


回答1:


XmlSerializer will simply not trust you to produce valid xml from a string. If you want a member to be ad-hoc xml, it must be something like XmlElement. For example:

[XmlElement("body")]
public XmlElement Body {get;set;}

with Body an XmlElement named random with InnerText of "This could be any rondom piece of unknown xml" would work.


[XmlRoot("object")]
public class Outer
{
    [XmlElement("stuff")]
    public Inner Inner { get; set; }
}
public class Inner
{
    [XmlElement("body")]
    public XmlElement Body { get; set; }
}

static class Program
{
    static void Main()
    {
        var doc = new XmlDocument();
        doc.LoadXml(
           "<random>This could be any rondom piece of unknown xml</random>");
        var obj = new Outer {Inner = new Inner { Body = doc.DocumentElement }};

        new XmlSerializer(obj.GetType()).Serialize(Console.Out, obj);
    }
}


来源:https://stackoverflow.com/questions/8833263/serialize-xml-with-xml-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!