How to get the last node using XPath in C #?
I have the following part of the xml file.
<UN N="@U1"> <DT N="24/06/2011"> <PN N="@P1"> <TM N="02:24:11"> <JB T="GP"> <A>notepad</A> <Z>Notepad</Z> <N>Untitled - Notepad</N> <J>1;0;1;1;0;0</J> <C>0.00500;0.09500;0.03500</C> <S>1;0;1;1</S> <P>0;0</P> <F>0</F> </JB> </TM> </PN> </DT> <DT N="23/06/2011"> <PN N="@P1"> <TM N="02:38:49"> <JB T="PAGP"> <A>notepad</A> <Z>Notepad</Z> <N>Untitled - Notepad</N> <J>1;1;1;1;0;1</J> <C>0.00500;0.09500;0.03500</C> <S>1;1;0;0</S> <P>1;1</P> <F>0</F> </JB> </TM> </PN> </DT> ..... ..... </UN> I need to get the last node where PN N = @ P1.
Sample request will be appreciated.
Thanks in advance.
The last() XPath function can be used to find the last of a node. So the last <PN> node with the N attribute having the value @P1 will be:
//PN[@N='@P1'][position() = last()] The .NET code will depend on which XML interface you are using: XmlDocument , XPathDocument or LINQ to XML ( XDocument ). (The approach with XmlReader must be loaded into one of three, and then use it.)
Edit (based on comment) To return the child <F> last <PN> with the attribute as above, where xDoc is an instance of XmlDocument :
var foundNode = xDoc.SelectSingleNode("//PN[@N='@P1'][position() = last()]/TM/JB/F"); Edit # 2 (based on another comment): return the last <PN> , where each <DT> can contain several <DT> 1 elements for all <DT> elements.
Testing this with some better XML example (see below) using XmlElement.SelectNodes and then iterating over the returned node set showed that the right node was found, it just wasn't the first and therefore the SelectSingleNode was not returned. This is the key: the last() predicate was used in every mapping //PN[@N='@P1'] . A quick change of priority was all that was needed:
(//PN[@N='@P1'])[last()] 1 For further use, if several elements are possible, then show at least two in the sample, otherwise readers will only accept singular copies. Also, you do not need to delete all nodes (for example, children):
The XML sample I used for testing (x attributes added to simplify the identification of the element selected during testing):
<UN N='@U1'> <DT N='24/06/2011'> <PN N='@P1' x='#1'/> <PN N='@P1' x='#2'/> <PN N='@P2' x='#3'/> </DT> <DT N='24/06/2011'> <PN N='@P1' x='#4'/> <PN N='@P1' x='#5'/> <PN N='@P2' x='#6'/> </DT> <DT N='24/06/2011'> <PN N='@P3' x='#7'/> <PN N='@P4' x='#8'/> <PN N='@P5' x='#9'/> </DT> </UN>