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.
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.
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.
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.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With