Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put the <!CDATA> in a XML tag

Tags:

c#

xml

I'm trying to put <!CDATA> in a specific tag in my XML file, but the result is &lt;![CDATA[mystring]]&gt;

Someone can help me ?

The encoding

XmlProcessingInstruction pi = doc.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");

How I'm doing

texto.InnerText = "<![CDATA[" + elemento.TextoComplementar.ToString() + "]]>";
like image 850
Lucas_Santos Avatar asked Oct 02 '12 12:10

Lucas_Santos


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 " ]]> ".

Can we use CDATA in XML attribute?

The spec says that the Attribute value must not have an open angle bracket. Open angle brackets and ampersand must be escaped. Therefore you cannot insert a CDATA section.

What is CDATA tag 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.

Can you use CDATA in HTML?

Note that CDATA sections should not be used within HTML; they only work in XML.


2 Answers

XmlNode xnode = xdoc.SelectSingleNode("entry/entry_status");

XmlCDataSection CData;

InnerText performs whatever escaping is required.

xnode.InnerText = "Hi, How are you..??";

If you want to work with CDATA node then:

CData = doc.CreateCDataSection("Hi, How are you..??");
like image 145
Vishal Suthar Avatar answered Sep 28 '22 09:09

Vishal Suthar


You haven't explained how you are creating the XML - but it looks like it's via XmlDocument.

You can therefore use CreateCDataSection.

You create the CData node first, supplying the text to go in it, and then add it as a child to an XmlElement.

You should probably consider Linq to XML for working with XML - in my most humble of opinions, it has a much more natural API for creating XML, doing away with the XML DOM model in favour of one which allows you to create whole document trees inline. This, for example, is how you'd create an element with an attribute and a cdata section:

var node = new XElement("root", 
  new XAttribute("attribute", "value"),
  new XCData("5 is indeed > 4 & 3 < 4"));
like image 34
Andras Zoltan Avatar answered Sep 28 '22 09:09

Andras Zoltan