Search code examples
c#.netxmlcdata

Retrieving Value of an XElement where value is <![CDATA[12345]]>


If i have the following xml element:

 <TEST><![CDATA[12345]]></TEST>

I'm trying to extract the value of a <TEST> xml element using below code:

  XElement elem = documet.XPathSelectElement(xpath_to_TEST); //xpath_to_TEST is the actual xpath to that element
  var value = elem.value //value of <TEST>

The problem with code above is that value variable contains 12345 where i want to get whole value of <TEST> as string including CDATA markups like <![CDATA[12345]]>.

Is this possible?


Solution

  • Try to treat the element content as XCData node, for example :

    XElement elem = documet.XPathSelectElement(xpath_to_TEST);
    XCData xcdata = (XCData)elem.FirstNode;
    Console.WriteLine(xcdata.ToString());
    //above prints :
    //<![CDATA[12345]]>
    

    related question : How to do edit text content keeping it in a CDATA block?