Monday, 16 February 2015

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



So, I have an XML file like the following structure,



<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>


I want to select all , if attribute [@Type] of is 1 and attribute [@TimePeriod] of is M1.


I've loaded in an XElement names xElement. Then, I'm using



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


This supposed to select only the 1st and 2nd from the above XML file. Instead it is selecting all . What am I doing wrong?


I've tried using 'and' instead of '|' in the code. But it's not working at all and throwing exception.


Any suggestions guys? Thanks in advance.


No comments:

Post a Comment