使用XML字符串序列化XML

时间:2012-01-12 10:09:11

标签: c# .net xml serialization xml-serialization

我必须生成以下XML

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

我已经将它映射到一个类,其body属性为string。

如果我将正文设置为字符串值:“<random>This could be any rondom piece of unknown xml</random>

字符串在序列化期间被编码。我怎么能不编码字符串,以便它被写为原始XML?

我还希望能够对此进行反序列化。

1 个答案:

答案 0 :(得分:6)

XmlSerializer根本不信任您从string生成有效的xml。如果您希望成员是ad-hoc xml,则它必须类似于XmlElement。例如:

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

Body XmlElement random InnerText "This could be any rondom piece of unknown xml" [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); } } 将起作用。


{{1}}