Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write CData in xml

Tags:

i have an xml like :

<?xml version="1.0" encoding="UTF-8"?> <entry>     <entry_id></entry_id>     <entry_status></entry_status>   </entry> 

i am writing data in it like:

XmlNode xnode = xdoc.SelectSingleNode("entry/entry_status"); xnode.InnerText = "<![CDATA[ " + Convert.ToString(sqlReader["story_status"]) + " ]]>" ;     

but its change "<" to "&lt" of CDATA. Please tell me how to fill values in above xml as a CData format.

i know that we can create CDATA like :

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

but my process is to read node of xml and change its value not to append in it. Thanks

like image 816
Dr. Rajesh Rolen Avatar asked Jan 13 '11 11:01

Dr. Rajesh Rolen


People also ask

How do I add CDATA to XML?

CDATA sections may be added anywhere character data may occur; they are used to escape blocks of text containing characters which would otherwise be recognized as markup. CDATA sections begin with the string " <! [CDATA[ " and end with the string " ]]> ".

What is the CDATA in XML?

A CDATA section is used to mark a section of an XML document, so that the XML parser interprets it only as character data, and not as markup. It comes handy when one XML data need to be embedded within another XML document.

How do I get CDATA from XML?

In current Java DOM implementation you can access CDATA simply as text data using e. getTextContent() . See example without type check, cast, e. getData() .

What is the correct syntax of the CDATA section in an XML document?

A CDATA section begins with the character sequence <! [CDATA[ and ends with the character sequence ]]>. Between the two character sequences, an XML processor ignores all markup characters such as <, >, and &. The only markup an XML pro-cessor recognizes inside a CDATA section is the closing character sequence ]>.


2 Answers

As described here: msdn

// Create an XmlCDataSection from your document var cdata = xdoc.CreateCDataSection(Convert.ToString(sqlReader["story_status"]));  // Append the cdata section to your node xnode.AppendChild(cdata); 
like image 126
Nekresh Avatar answered Oct 13 '22 16:10

Nekresh


Do you really need it to be in CDATA, or do you just want to get the text in there in a way which won't require extra escaping in your code?

InnerText performs whatever escaping is required, so generally I'd just use

xnode.InnerText = Convert.ToString(sqlReader["story_status"]); 

... but if you really want a CDATA node, you can create one yourself as per Nekresh's answer.

like image 27
Jon Skeet Avatar answered Oct 13 '22 15:10

Jon Skeet