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?

Était-ce utile?

La 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();

Autres conseils

I went with

var newValue = element.Value.Replace("> 22/7", "< 22/7");
element.ReplaceNodes(new XCData(newValue));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top