Michael Kniskern
Michael Kniskern

Reputation: 25280

parse XML using LINQ to XML

I have the following XML node:

<reportDataRow>
    <columnData colNum="1">
        <data>FirstName</data>
    </columnData>
    <columnData colNum="2">
        <data>LastName</data>
    </columnData>
</reportDataRow>

I want to retrieve the value from the data node based on the value of the colNum attribute in the columnData node.

How would I accomplish that using LINQ?

Upvotes: 0

Views: 360

Answers (2)

labroo
labroo

Reputation: 2961

again assuming reportDataRow is an XElement and value is a variable that you want to match the colNum attribute with;

foreach (var selected in reportDataRow.Elements("columnData").Where(a =>a.Attribute("colNum").Value == value))
        {
            yield return selected.Element("data").Value;
        }

usage will change based on how you want it

Upvotes: 3

James Sulak
James Sulak

Reputation: 32457

The easiest way is to use XPathSelectElement. Assuming that reportDataRow is an XElement representing the root element, and value is a variable that you want to match the colNum attribute with:

reportDataRow.XPathSelectElement(".//data[parent::columnData/@colNum = '" + value + "']");

Upvotes: 2

Related Questions