Question

I want to edit the contents of a cdata block in this an document. Here's a simplified example:

<root><![CDATA[pi > 22/7]]></root>

I tried

var element = XElement.Parse("<root><![CDATA[pi > 22/7]]></root>");
element.Value = element.Value.Replace("> 22/7", "< 22/7");
element.Dump();

However, the result doesn't have a CDATA block.

<root>pi &lt; 22/7</root>

I wanted

<root><![CDATA[pi < 22/7]]></root>

How can I achieve that?

Was it helpful?

Solution

You need to modify value of the XCData element instead :

var element = XElement.Parse("<root><![CDATA[pi > 22/7]]></root>");
var cdata = (XCData)element.FirstNode;
cdata.Value = cdata.Value.Replace("> 22/7", "< 22/7");
element.Dump();

OTHER TIPS

I went with

var newValue = element.Value.Replace("> 22/7", "< 22/7");
element.ReplaceNodes(new XCData(newValue));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top