tags:

views:

283

answers:

2
<XMLDOC> 
<OPTIONA>   
    <![CDATA[
aaaaaaaaaaaaa     
]]>
    <![CDATA[
    bbbbbbbb]]>
<OPTIONA>
<OPTIONB>
    <![CDATA[
cccccccccccccccccccc      
]]>
    <![CDATA[
   dddddddddddddd]]>
</OPTIONB>
</XMLDOC>

How do I query say all CDATA's under OPTIONB?? using Linq-to-XML???

+3  A: 

The OPTIONB node is equivalent to:

<OPTIONB>
    <![CDATA[
cccccccccccccccccccc                    

   dddddddddddddd]]>
</OPTIONB>

So to get the value inside the CData section you could use the following:

var cdata = XElement.Load("test.xml").Element("OPTIONB").Value;

You will not be able to get the CData values separately because they have the same semantics as if it was a single CData section for a XML parser.

Darin Dimitrov
provided solution does not work in common - if element contains text or other nodes your code will return _wrong_ result
Sergey Mirvoda
This answer will work for most cases. Just to clarify for Mirvoda edge case, calling `.Value` on anything is the equivalent of concatenating the `.Value` strings of every sub-element together (text and CDATA are technically sub-elements) in the order they appear.`new XElement("test", "some non-cdata text", new XElement("a", "avalue"), new XCData("some cdata`{line break}`is in here"), new XElement("b", "bvalue", new XElement("subb", "subbvalue")), "some more non-cdata text").Value`...becomes...`some non-cdata textavaluesome cdata`{line break}`is in herebvaluesome more non-cdata text`
patridge
+1  A: 
XElement.Load("test.xml")
 .Element("OPTIONB")
   .Nodes()
     .Where(x=>x is XCData).First().Cast<XCData>().Value
Sergey Mirvoda