Search code examples
xmllinqcdata

linq to xml CDATA problem


When I used linq to retrieve xml, <CDATA[[ ]]> is removed, which is what I want to achieve.

But when I save the file, <CDATA[[ ]]> becomes &lt;CDATA[[ ]]&gt; in the xml file. Whether or not I explicitly append with <CDATA[[ ]]> before saving gives me the same result.

Tried appending with &lt;CDATA[[ ]]&gt; but still gives me the same result.
Is there any other way to make it show <CDATA[[ ]]> in the xml file?

I'm using Encoding.UTF8.GetBytes() to write to the file after saving the XDocument using XDocument.Save(System.IO.StringWriter).


Solution

  • not 100% sure what you are asking here, but it seems to be how do I create a CData section in your XElement. It's actually very simple just use the XCData object.

    yourXElement.Add(new XElement("SomeNode", new XCData("Some CData content")));
    

    When you are reading it, as you already see, you don't need to do anything special, the cast operator overload will extract the data for you i.e.

    string myCdata = (string)xe.Element("SomeNode");