I receive an object from another application and need to serialize it into XML. The object contains several properties and one of them contains already serialized part of XML.
How can I keep it as it is during serialization to XML?
Currently I am using XmlSerializer, but the problem is that it escapes some characters (< and >) and serializes property as a value of XML node.
Example, object structure:
public class SomeObject
{
public string A{get;set;}
public string B {get;set;}
//contains part of XML
public string C {get;set;}
}
Instance:
var a = new SomeObject
{
A = "A",
B = "B",
C = "<C1>test</C1><C2>test 2</C2><C3>test 2</C3>"
};
I need to keep C value as it is:
<SomeObject>
<A>A</A>
<B>B</B>
<C><C1>test</C1><C2>test 2</C2><C3>test 2</C3></C>
</SomeObject>
Instead, the result looks differently (which is expected, but not what I need):
<SomeObject>
<A>A</A>
<B>B</B>
<C><C1>test</C1><C2>test 2</C2><C3>test 2</C3></C>
</SomeObject>
Code that I am using for serialization:
public string Serialize(object obj)
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
var xmlserializer = new XmlSerializer(obj.GetType(), "");
var stringWriter = new StringWriter();
var settings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8, OmitXmlDeclaration = true };
using (var writer = XmlWriter.Create(stringWriter, settings))
{
xmlserializer.Serialize(writer, obj,ns);
return stringWriter.ToString();
}
}
Of course, I can create another object where C will be type of class and deserialize my C to that object, and then serialize that object. It will be serialized to the correct object, exactly what I need. But I want to avoid all those additional serialization/deserialization operations.
Is there a way to specify for the serializer that the property should not be additionally serialized?