Joh*_*ohn 6 .net c# xml serialization xml-serialization
我必须生成以下XML
<object>
<stuff>
<body>
<random>This could be any rondom piece of unknown xml</random>
</body>
</stuff>
</object>
Run Code Online (Sandbox Code Playgroud)
我已经将它映射到一个类,其body属性为string类型.
如果我将主体设置为字符串值:" <random>This could be any rondom piece of unknown xml</random>"
字符串在序列化期间被编码.我怎么能不编码字符串,以便它被写为原始XML?
我也希望能够反序化.
XmlSerializer根本不信任你从a生成有效的xml string.如果你想要一个成员是ad-hoc xml,它必须是这样的XmlElement.例如:
[XmlElement("body")]
public XmlElement Body {get;set;}
Run Code Online (Sandbox Code Playgroud)
有Body一个XmlElement名叫random用InnerText的"This could be any rondom piece of unknown 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);
}
}
Run Code Online (Sandbox Code Playgroud)