Search code examples
c#.netxpathxmldocument

How can I get those last XML items using xPath or anything else?


I've used the child elements of the first node PovprecnaPlaca before I noticed I need the child elements of the last one.

Picture of XML for reference:

Picture of XML for reference

Appreciate all the helpful answers!

XML looks like this:

<PovprecnaPlaca>
   <Datum>2017-07-01T00:00:00</Datum>
   <BrutoPlacaZadnje3Mesece>1603,00</BrutoPlacaZadnje3Mesece>
   <NetoPlacaZadnje3Mesece>1045,12</NetoPlacaZadnje3Mesece>
   <BrutoPlaca>1593,10</BrutoPlaca>
   <NetoPlaca>1039,55</NetoPlaca>
 </PovprecnaPlaca>
 <PovprecnaPlaca>
   <Datum>2017-08-01T00:00:00</Datum>
   <BrutoPlacaZadnje3Mesece>1602,98</BrutoPlacaZadnje3Mesece>
   <NetoPlacaZadnje3Mesece>1045,45</NetoPlacaZadnje3Mesece>
   <BrutoPlaca>1613,62</BrutoPlaca>
   <NetoPlaca>1051,73</NetoPlaca>
  </PovprecnaPlaca>
 </Place>
</PovprecnePlace>

Solution

  • Get Datum node from the last PovprecnaPlaca of each Place.

    var nodes = xdoc.XPathSelectElements("//PovprecnaPlaca[last()]/Datum");
    

    Get the text inside each node.

    List<string> results = nodes.Select(d => d.Value).ToList();
    

    Two reasons why your attemp didn't work: 1) It starts from root node "/" of the document and there's no PovprecnaPlaca node at this level. 2) By calling text() it's getting XText which raises an exception in Linq as it expects nodes as a result when calling XPathSelectElements().