问题
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.
回答1:
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);
}
}
来源:https://stackoverflow.com/questions/8833263/serialize-xml-with-xml-string