我在将以下 XPath 查询转换为 LINQ 时遇到了问题。我不确定如何处理 position() 方法,因为我找不到 LINQ 等效方法。
(//table[@border='1'])[1]//tr[position() > 1 and position() < last()]
此外,我在查询中找不到 .//
的 LINQ 版本:
.//div[span/@title='Event group']
有人可以帮我翻译这些吗?
最佳答案
这部分你的 XPath (//table[@border='1'])[1]
, 可以大致翻译成以下 LINQ(假设 doc
是 XDocument
的一个实例):
doc.Descendants("table")
.Where(o => (string)o.Attribute("border") == "1")
.FirstOrDefault()?
还有这个表达式 //tr[position() > 1 and position() < last()]
, 大致翻译为:
.Descendants("tr").Where(o => {
var trs = o.Parent.Elements("tr").ToList();
var position = trs.IndexOf(o)+1; //since XPath position index starts from 1
return position > 1 && position < trs.Count;
})
从上面两个例子,你应该可以看出如何表达//
, position()
, 和 @attribute
在林克。翻译你的第二个 XPath 留作练习 :)
关于c# - 将 XPath 转换为 LINQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36562236/