使用 XML 字符串序列化 XML

发布于 2024-12-26 12:40:38 字数 423 浏览 1 评论 0原文

我必须生成以下 XML,

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

我已将其映射到一个类,其主体属性为字符串类型。

如果我将正文设置为字符串值:“这可能是未知 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>

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少女七分熟 2025-01-02 12:40:38

XmlSerializer 根本不信任您从字符串 生成有效的xml。如果您希望成员是临时 xml,则它必须类似于 XmlElement。例如:

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

使用 Body 命名为 randomXmlElementInnerText“这可以是任何随机块未知的 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);
    }
}

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);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文