Silentbob
Silentbob

Reputation: 3065

How to get the value from a XML Document

I am trying to extract the values from the following xml sample:

<myPrices>
  <Prices Date="10-Oct-18" ReportName="myReport">
    <Record RecordId="1">
      <COLUMN DisplayName="Start Date" FormalName="startdate">11.10.2018</COLUMN>
      <COLUMN DisplayName="End Date" FormalName="Price">10</COLUMN>
    </Record>
    <Record RecordId="2">
      <COLUMN DisplayName="Start Date" FormalName="startdate">11.10.2018</COLUMN>
      <COLUMN DisplayName="End Date" FormalName="Price">20</COLUMN>
    </Record>
  </Prices>
</myPrices>

So for the above I want the values 10 and 20.

I have the following so far (from Stackoverflow link) but this gives me the value for FormalName i.e. startdate and price.

string[] arr = new string[3];
var dr = from n in prices.Descendants("COLUMN")
         select new string[]
         {
             arr[0] = n.Attribute("FormalName").Value
         };

foreach (var item in dr)
{
    dt.Rows.Add(item[0]);
}

Upvotes: 0

Views: 90

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

You are getting the value of FormalName because that is what you are selecting. What you want is to filter out only COLUMNs where their attribute of FormalName equals "Price" and then retrieve the value of the element:

var result = prices.Descendants("COLUMN")
                   .Where(e => e.Attribute("FormalName")?.Value == "Price")
                   .Select(e => e.Value);

Which IMO will look now a bit cleaner in query syntax:

var result = from c in prices.Descendants("COLUMN")
             where c.Attribute("FormalName")?.Value == "Price"
             select c.Value;

Upvotes: 1

Related Questions