Serializing XML with an XML String

I need to create the following XML

<object> <stuff> <body> <random>This could be any rondom piece of unknown xml</random> </body> </stuff> </object> 

I matched this with a class with a body property of type string.

If I set the body to a string value: " <random>This could be any rondom piece of unknown xml</random> "

The string is encoded during serialization. How can I not encode a string so that it is written as raw XML?

I also want to be able to deserialize this.

+6
source share
1 answer

XmlSerializer simply does not trust you to create valid xml from string . If you want the member to be ad-hoc xml, it should be something like XmlElement . For instance:

 [XmlElement("body")] public XmlElement Body {get;set;} 

with Body a XmlElement named random with InnerText of "This could be any rondom piece of unknown xml" will 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); } } 
+5
source

Source: https://habr.com/ru/post/905808/


All Articles