dinotom
dinotom

Reputation: 5162

Getting sub element value using XPath where date is the element value

Given this sample xml

<?xml version="1.0" encoding="UTF-8"?>
<currencies>
  <currency value="gbp">
   <Date>11/5/2020</Date>
   <Close>1.3102</Close>
 </currency>
 <currency value="gbp">
   <Date>11/4/2020</Date>
   <Close>1.2988</Close>
 </currency>
 <currency value="gbp">
   <Date>11/3/2020</Date>
   <Close>1.3049</Close>
 </currency>
</currencies>

I can get all the nodes by currency using

var xpath = $"//currencies//currency[@value='{currency}']";
var nodes = doc.XPathSelectElements(xpath);

But I cannot get the syntax right to get the node by date

 //priceDate is a DateTime passed in
 //this produces this xpath --- //currencies//currency[@value='gbp'] 
 [Date[text()] =09/15/2015]
 var xpath = $"//currencies//currency[@value='{currency}'][Date[text()] ={priceDate:MM/dd/yyyy}]";
 var node = doc.XPathSelectElement(xpath);

Any help appreciated. I will ultimately want to retrieve the Close price in the xpath too.

Upvotes: 1

Views: 274

Answers (1)

Yitzhak Khabinsky
Yitzhak Khabinsky

Reputation: 22167

You need to pay attention to the date formatting. With leading zeros or without...

Select currency element by the date:

/currencies/currency[Date='11/4/2020']

Select Close element by the date:

/currencies/currency[Date='11/4/2020']/Close

Upvotes: 1

Related Questions