How to do edit text content keeping it in a CDATA

2019-08-28 05:35发布

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?

2条回答
ら.Afraid
2楼-- · 2019-08-28 05:47

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();
查看更多
姐就是有狂的资本
3楼-- · 2019-08-28 05:59

I went with

var newValue = element.Value.Replace("> 22/7", "< 22/7");
element.ReplaceNodes(new XCData(newValue));
查看更多
登录 后发表回答