Bopsi
Bopsi

Reputation: 2456

Extract and Modify cdata section of xml using c#

I have the following xml

<parent>
    <child>abra</child>
    <child>kadabra</child>
    <child>alakazam</child>
    <![CDATA[ some data here ]]>
</parent>

I want to extract the cdata section, what I have done is - converted the data into string and extracted it with the following code

string toText = xmlDoc.OuterXml.Substring(xmlDoc.OuterXml.IndexOf("<![CDATA[") + "<![CDATA[".Length);
toText = toText.Remove(toText.IndexOf("]]>"));

where xmlDoc is XMLDocument which contails above xml

Is there any better way of doing this?

I googled a lot, but what I got is extraction of cdata section only if its the only child of its parent element.

Finally I want to modify cdata section and modify the current xml as

<parent>
    <child>abra</child>
    <child>kadabra</child>
    <child>alakazam</child>
    <![CDATA[ modified data here ]]>
</parent>

Upvotes: 4

Views: 6245

Answers (1)

har07
har07

Reputation: 89325

Given this valid XML sample :

<parent>
    <child>1</child>
    <child>2</child>
    <child>3</child>
    <![CDATA[ some data here ]]>
</parent>

Since the only text node that is direct child of <parent> is the cdata section you want to get, you can do this way to select the cdata section and modify it's content :

var cdata = (XmlCDataSection)xmlDoc.SelectSingleNode("/parent/text()");
cdata.InnerText = " modified data here ";
Console.WriteLine(xmlDoc.OuterXml);

Another possible approach is using XDocument to replace the older library, XmlDocument :

var doc = XDocument.Load("path_to_your_xml");
var xcdata = doc.DescendantNodes().OfType<XCData>().FirstOrDefault();
xcdata.Value = " modified data here ";
Console.WriteLine(doc.ToString());

The output is as follow (formatted for readability) :

<parent>
    <child>1</child>
    <child>2</child>
    <child>3</child>
    <![CDATA[ modified data here ]]>
</parent>

Upvotes: 7

Related Questions