Search code examples
c#linq-to-xmlcdata

Read CDATA section based on where clause using LINQ


I am trying to read CDATA section of an xml node based upon the where clause.

<Book>
  <BookItem ISBN="SKS84747"><![CDATA[20]]> </BookItem>
  <BookItem ISBN="LHKGOI84747"><![CDATA[50]]> </BookItem>
  <BookItem ISBN="PUOT84747"><![CDATA[20]]> </BookItem>
</Book>

This code gives me all the CDATA sections,

var value = from v in x.Descendants("BookItem").OfType<XCData>()
                                select (string)v.Value;

How to put where clause based on ISBN ? How can I read this CDATA using LINQ to XML.


Solution

  • var value = x.DescendantNodes().OfType<XCData>()
                    .Where(m => m.Parent.Name == "BookItem" && m.Parent.Attribute("ISBN").Value == "PUOT84747")
                    .ToList();
    

    or

    before ToList()

    .Select(cdata => cdata.Value.ToString());