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.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.