xpath 选择具有最后一个子值的元素 [英] xpath to select elements with last child value
问题描述
这是我的xml文件
<profiles>
<profile id='8404'>
<name>john</name>
<name>mark</name>
</profile>
<profile id='8405'>
<name>john</name>
</profile>
</profiles>
并且我想选择最后一个名称"子值= john 的配置文件,结果应该只包含 id=8405 的配置文件可以评估这个的 xpath 是什么?
and I want to select profiles where last "name" child value= john, the result should contains the profile with id=8405 only what it the xpath that can evaluate this?
这是我的试验:
var filterdFile = profilefileXML.XPathSelectElements("/profiles/profile[name[last()]='john']");
但这没有意义.
更新:我的跟踪是正确的,其中只有一个语法错误.谢谢大家
Updated: My trail is correct, there was only a syntax error in it. Thanks all
推荐答案
您可以使用连续的 [...]
应用多个索引操作:
You can apply multiple indexing operations with successive [...]
:
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
这将返回包含元素 name
的最后一个 profile
元素,其值为 john
.
This will return the last profile
element that contains the element name
with a value of john
.
另一方面,如果您想返回 所有元素,其中最后一个 name
元素的值为 john
,那么您的 XPath 应该已经可以工作了:
If you on the other hand want to return all elements which last name
element has a value of 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);
}
这篇关于xpath 选择具有最后一个子值的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!