Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize XML with XML string

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.

like image 989
John Avatar asked Jan 12 '12 10:01

John


People also ask

What is the correct way of using XML serialization?

XML Serialization Considerations Type identity and assembly information are not included. Only public properties and fields can be serialized. Properties must have public accessors (get and set methods). If you must serialize non-public data, use the DataContractSerializer class rather than XML serialization.

What does serialize XML mean?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

Is XML serializable?

XML serialization can take more than one form, from simple to complex. For example, you can serialize a class that simply consists of public fields and properties, as shown in Introducing XML Serialization.

What is serialization XML Java?

Serialization of Java Objects to XML can be done using XMLEncoder, XMLDecoder. Java Object Serialization feature was introduced in JDK 1.1. Serialization transforms a Java object or graph of Java object into an array of bytes which can be stored in a file or transmitted over a network.


1 Answers

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);
    }
}
like image 61
Marc Gravell Avatar answered Sep 29 '22 08:09

Marc Gravell