【问题标题】:Getting sub element value using XPath where date is the element value使用 XPath 获取子元素值,其中日期是元素值
【发布时间】:2021-02-18 12:37:25
【问题描述】:

鉴于此示例 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>

我可以使用货币获取所有节点

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

但我无法正确获取按日期获取节点的语法

 //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);

任何帮助表示赞赏。 我最终也想在 xpath 中检索收盘价。

【问题讨论】:

    标签: c# xml xpath


    【解决方案1】:

    您需要注意日期格式。带前导零或不带...

    按日期选择货币元素:

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

    按日期选择关闭元素:

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

    【讨论】:

    • @YitzhakKhabinsky 我已经试过这个 var xpath = $"//currencies//currency[@value='{currency}'][Date ='{priceDate:MM/dd/yyyy}'] ";但它产生一个空结果,我验证了 xml 在文件中
    • 并且生成的 XPath 字符串看起来与您在回答中注明的完全相同(包括属性)//currencies//currency[@value='gbp'][Date ='09/15/2015' ]
    • 我发现了问题...例如 priceDate 变量转换为 09/15/2015,但文件的日期为 9/15/2015。从月份和日期中删除前导 0 的货币格式是什么
    • @dinotom,我从一开始就在回答中提到了零。
    • @YitzhakKhabinsky 是的,这就是我回去检查它的原因。此 XPath 现在正在运行 $"//currencies//currency[@value='{currency}'][Date ='{priceDate:M/d/yyyy}']//Close"
    猜你喜欢
    • 2014-08-09
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    相关资源
    最近更新 更多