0

i am trying to Create XML document that contains another xml inside like child.

So first of all i have object Foo that have some properties. I serialize it with this function:

private static string SerializeToString(object dataToSerialize)
{
    var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
    var serializer = new XmlSerializer(dataToSerialize.GetType());
    var settings = new XmlWriterSettings
    {
        Indent = true,
        OmitXmlDeclaration = true
    };
    using (var stream = new StringWriter())
    using (var writer = XmlWriter.Create(stream, settings))
    {
        serializer.Serialize(writer, dataToSerialize, emptyNamepsaces);
        return stream.ToString();
    }
}

In another class where i don't have access to Foo class I need to save some data with this Foo string inside xml document. So i have another object like this:

public class Bar
{
    public int SomeInt { get; set; }

    public string FooString { get; set; }
}

When i serialize this Bar object and save it like xml document. I get something like this for FooString element.

<FooString>
        <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">&lt;Foo&gt;
  &lt;Guid&gt;2de0b223-308a-4c90-8dc7-09b48c1f42e6&lt;/Guid&gt;
  &lt;Id&gt;119&lt;/Id&gt;
  &lt;Name&gt;Some name&lt;/Name&gt;
  &lt;Description&gt;SomeDesc..&lt;/Description&gt;
&lt;/Foo&gt;</string>
  </FooString>

I understand that this HTML Character Entities (&lt;) are there because its saved as string. But it is possible to save it without this characters? But i only saved it like string because i don't have access to Foo class.. so i don't know what parameters it could have.. that's why i save it like string and send it to Bar class. It is possible to save it as something else like e.g. XmlElement or i don't know what... that will also show structure of Foo object in Bar serialized xml??.. Thank You !!

Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
Pavol
  • 552
  • 8
  • 19

1 Answers1

0

The best way to have xml in xml is to have Foo Property, not FooString in your class. If you use xml as a string you couldn't be sure, that it is still valid xml, it's just a string. If you don't want or couldn't serialize xml as data, i would advice to serialize Foo as CData, something like:

public class Bar
{
    public int SomeInt { get; set; }

    [XmlIgnore]
    public string FooString { get; set; }
    [XmlElement("FooString")]
    public XmlCDataSection FooStringCData
    {
        get { return new XmlDocument().CreateCDataSection(FooString); }
        set { FooString = (value != null) ? value.Data : null; }
    }
}

That gives you output of your xml + xml string in CData section:

<Bar>
  <SomeInt>1</SomeInt>
  <FooString><![CDATA[<Z>
  <A>10</A>
  <B>12</B>
</Z>]]></FooString>
</Bar>
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49