0

I have an XML file, where almost all of the inner text values are stored in CDATA. Now I've created an application that is able to read in the entire XML document with XmlReader, store the data into specific classes, adjust the data, and finaly create a new document with all of my changes. This works perfectly.

The only thing that I can't seem to get to work, is to append CDATA trough serialization on a XmlText element. For example:

This is my Text element. And it contains a property Text of type XmlText.

[XmlRoot(ElementName = "Text")]
public class Tekst
{
  [XmlAttribute(AttributeName = "Lang")]
  public string Lang { get; set; }
  
  [XmlText]
  public string Text { get; set; }
}

And this is the implementation:

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
Tekst tekst = new Tekst();
tekst.Text = "Hello world";
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Tekst));
using(XmlWriter writer = XmlWriter.Create("C:\\Users\\user_1\\Desktop\\test.xml"))
{
    xmlSerializer.Serialize(writer ,tekst, ns);
}

My Output:

<?xml version="1.0" encoding="utf-8"?><Text>Hello world</Text>

I want an output like this:

 <?xml version="1.0" encoding="utf-8"?><Text><![CDATA[Hello world]]</Text>

I've tried various solutions, but none of them seem to work on XmlText node types. I am able to convert other elements of type XmlElement like this (found on: How do you serialize a string as CDATA using XmlSerializer?):

[XmlIgnore]
public string ExampleString{ get; set; }
[XmlElement(ElementName = "ExampleString")]
public XmlCDataSection ExampleStringCDATA
{
    get
    {
        return new XmlDocument().CreateCDataSection(ExampleString);
    }
    set
    {
        ExampleString = value.Value;
    }
}

Any help would be appreciated. Thank you!

UPDATE I found out that it was not nessecary to add CDATA to every text value. The program that needs to read this xml file is able to read it whitouth CDATA. So i got my program working now!

I'm still interested in the solution tho.

  • I think [this answer specifically](https://stackoverflow.com/a/1379936/3744182) to [How do you serialize a string as CDATA using XmlSerializer?](https://stackoverflow.com/q/1379888/3744182) should do what you want. Agree? – dbc Apr 23 '21 at 13:00
  • Yes, that works. See https://dotnetfiddle.net/nq96ls – dbc Apr 23 '21 at 13:07

0 Answers0