Xpath to select items with last child value

This is my xml file

<profiles> <profile id='8404'> <name>john</name> <name>mark</name> </profile> <profile id='8405'> <name>john</name> </profile> </profiles> 

and I want to select profiles where the last child value is "name" = john, the result should only contain a profile with id = 8405 what is xpath that can evaluate this?

here is my test:

  var filterdFile = profilefileXML.XPathSelectElements("/profiles/profile[name[last()]='john']"); 

but that doesn't make sense.

Updated: My path is correct, it only had a syntax error. Thank you all

+4
source share
2 answers

You can apply several indexing operations with sequential [...] :

 var doc = XDocument.Parse(xml); //the xml from your question var node = doc.XPathSelectElement("/profiles/profile[name='john'][last()]"); Console.WriteLine(node.Attribute("id").Value); //outputs 8405 

This will return the last profile element containing the name element with the value john .

If on the other hand you want to return all elements for which the last name element has the value john , your XPath should work already:

 var nodes = doc.XPathSelectElements("/profiles/profile[name[last()]='john']"); foreach (var node in nodes) { Console.WriteLine(node.Attribute("id").Value); } 
+3
source

You can also try LINQ

 XDocument xDoc = XDocument.Load("data.xml"); var matches = xDoc.Descendants("profile") .Where(profile => XElement.Parse(profile.LastNode.ToString()).Value == "john"); 

And you can access xml data with foreach

 foreach(XElement xEle in lastEle) { var xAttribute = xEle.Attribute("id"); if (xAttribute != null) { var id = xAttribute.Value; } var lastName = XElement.Parse(xEle.LastNode.ToString()).Value; } 
0
source

Source: https://habr.com/ru/post/1447674/


All Articles