How to do edit text content keeping it in a CDATA

2019-08-28 05:13发布

问题:

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?

回答1:

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


回答2:

I went with

var newValue = element.Value.Replace("> 22/7", "< 22/7");
element.ReplaceNodes(new XCData(newValue));