Thursday, 29 November 2007

XmlNode and how to add CDATA to it

All I needed to do was create via C# an XML file that included some CDATA sections:

<description><![CDATA[<P>hello world</P>]]></description>

After looking at the XmlDocument MSDN pages, it looked to be as simple as I had hoped. I ventured forth and created the following c#:

XmlNode itemDescription = doc.CreateNode("cdatasection", "description", "");
itemDescription.InnerText = post.PostedText;

But that code created this monstrosity:

<![CDATA[<P>hello world</P>]]> .... weird??!

After some experimenting I finally cracked it:

XmlNode itemDescription = doc.CreateElement("description");
XmlCDataSection cdata = doc.CreateCDataSection("<P>hello world</P>");

This code creates exactly what I need:

<description><![CDATA[<P>hello world</P>]]></description>

Hope this saves someone some time :)


Scott from Michigan said...

Awesome - this issue was driving me crazy until I found your blog post. Thanks for saving me what little hair I have left.


Neil kilbride said...

Glad it helped someone Scott :)

Anonymous said...

Nice, thanks!

Explotion said...
This comment has been removed by the author.
Anonymous said...

thanks a lot

Anonymous said...

Thanks, very helpful!

Anonymous said...

Thanx! It Helped! And Saved Time :D

Japanese Masshole said...

Yes. You saved me. Thanks!

Anonymous said...

Great! Thanks for the tip.