繁体   English   中英

如何在C#中使用XPath从不同的节点中根据2个属性选择一个值?

[英]How to select a value depending on 2 attributes from separate nodes using XPath in C#?

因此,我有一个类似以下结构的XML文件,

<Root>
  <Parent StoreDate="2014-12-31" Type="1">
    <Child1>2014-01-31</Child1>
    <Child2 TimePeriod="M1">
      <GrandChild1>-4.58849</GrandChild1>
      <GrandChild2>288</GrandChild2>
    </Child2>
  </Parent>
  <Parent StoreDate="2014-12-31" Type="1">
    <Child1>2014-02-28</Child1>
    <Child2 TimePeriod="M1">
      <GrandChild1>4.58015</GrandChild1>
      <GrandChild2>284</GrandChild2>
    </Child2>
  </Parent>
  <Parent StoreDate="2014-12-31" Type="1">
    <Child1>2014-03-31</Child1>
    <Child2 TimePeriod="M4">
      <GrandChild1>-0.65693</GrandChild1>
      <GrandChild2>284</GrandChild2>
    </Child2>
  </Parent>
  <Parent StoreDate="2014-12-31" Type="3">
    <Child1>2014-03-31</Child1>
    <Child2 TimePeriod="M1">
      <GrandChild1>-5.65693</GrandChild1>
      <GrandChild2>2334</GrandChild2>
    </Child2>
  </Parent>
</Root>

我想选择所有GrandChild1,如果Parent的属性[@Type]为1,Child2的属性[@TimePeriod]为M1。

我已经在名为xElement的XElement中加载了root。 然后,我正在使用

IEnumerable<XElement> elements = xElement.XPathSelectElements("(/Parent[@Type='1'] | /Parent[Child2/@TimePeriod='M1'])/Child2/GrandChild1");

应该从上面的XML文件中只选择第一个和第二个GrandChild1。 而是选择所有GrandChild1。 我究竟做错了什么?

我尝试使用“和”而不是“ |” 在代码中。 但是它根本不起作用并且抛出异常。

有什么建议吗? 提前致谢。

编辑:

我也想选择具有相同条件的Child1。 我需要做什么?

编辑:问题更改后添加代码以选择Child1。

选择Grand Child1的代码您可以使用//Parent[@Type='1']/Child2[@TimePeriod='M1']/GrandChild1

子项1选择XPath :(一种方法)

//Parent[@Type='1']/Child2[@TimePeriod='M1']/../Child1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM