views:

310

answers:

2

I want to replace text inside cdata section but when I simply trying to add text to it I lose CDATA definition.

I have a XML like this:

<title><![CDATA[string]]></title>

When I try to update this field with new value:

myXmlNode.SelectSingleNode("title").InnerText = TextBoxName.Text;

Output is

<title>string</title>

How do can I keep it as CDATA?

+2  A: 

The title element will have an CData child which needs to be cast like so:-

 ((XmlCDataSection)myXmlNode.SelectSingleNode("title").FirstChild).Value = TextBoxName.Text
AnthonyWJones
I was suspecting this was the way to do it, though you beat me to it while checking up the XmlCDataSection class.
Noldorin
Beat me too, though it does require a (obvious) cast.
Matthew Flaschen
@Matthew: Does something else need a cast? I don't see it?
AnthonyWJones
No, I meant the one you already have.
Matthew Flaschen
+1  A: 

I would do:

myXmlNode.SelectSingleNode("title").FirstChild.InnerText = TextBoxName.Text;

That way you don't have to deal with the CDATA format in your code (edit: hard-coding <![CDATA[ doesn't work anyway, as pointed out by Anthony)

Matthew Flaschen