Read CDATA section based on where clause using LINQ

Consider an XML as below;
<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;

In order to get CDATA of any particular node based on where clause we need to execute below query as,

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

This statement will return all the CDATA sections matching in where clause.
To get the single item just replace .ToList() with .Select(cdata => cdata.Value.ToString());

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

No comments:

Post a Comment