使用XML字符串序列化XML [英] Serialize XML with XML string

查看:47
本文介绍了使用XML字符串序列化XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须生成以下XML

I have to produce the following XML

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

我已将其映射到具有string类型的body属性的类.

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

如果我将主体设置为字符串值:"< random>这可能是任何未知的xml的rondom片段/random> "

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

字符串在序列化过程中得到编码.我如何不对字符串进行编码,以便将其写为原始XML?

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.

推荐答案

XmlSerializer 根本不信任您从 string 生成有效的xml.如果您希望成员是临时xml,则必须是 XmlElement 之类的东西.例如:

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

带有 Body

XmlElement 名为 random XmlElement ,其中 InnerText 未知的xml" 即可.

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

这篇关于使用XML字符串序列化XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆