Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将XPath转换为LINQ_C#_Linq_Xpath_Html Agility Pack - Fatal编程技术网

C# 将XPath转换为LINQ

C# 将XPath转换为LINQ,c#,linq,xpath,html-agility-pack,C#,Linq,Xpath,Html Agility Pack,我在将以下XPath查询转换为LINQ时遇到问题。我不确定如何处理position()方法,因为我找不到LINQ等价物 (//table[@border='1'])[1]//tr[position() > 1 and position() < last()] (//table[@border='1'])[1]//tr[position() > 1 and position() < last()] 有人能帮我翻译一下吗?这部分XPath(//table[@border=

我在将以下XPath查询转换为LINQ时遇到问题。我不确定如何处理position()方法,因为我找不到LINQ等价物

(//table[@border='1'])[1]//tr[position() > 1 and position() < last()]
(//table[@border='1'])[1]//tr[position() > 1 and position() < last()]

有人能帮我翻译一下吗?

这部分XPath
(//table[@border='1'])[1]
,可以大致翻译成以下LINQ(假设
doc
XDocument
的一个实例):

这个表达式
//tr[position()>1和position()
大致翻译为:

.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;
})
子体(“tr”)。其中(o=>{
var trs=o.Parent.Elements(“tr”).ToList();
var position=trs.IndexOf(o)+1;//因为XPath位置索引从1开始
返回位置>1&&position

从上面的两个示例中,您应该能够看到如何在LINQ中表达
/
position()
@attribute
。翻译第二个XPath只是一个练习:)

与其尝试进行直译,不如进行实际等效的查询

(//table[@border='1'])[1]//tr[position() > 1 and position() < last()]
(//table[@border='1'])[1]//tr[position() > 1 and position() < last()]
查询正在选择跳过第一行和最后一行的行。有更有效的方法来实现这一点

查询的第一部分是选择第一个有边框的表。然后将跳过第一行的行拿走,然后拿走除最后一行以外的所有行。如果不全数计算,就无法可靠地找出最后一个是什么


对于另一部分,等价于
/
的是调用
子体()


不能将XPath与LINQ一起使用吗@MarcinJuraszek我在解析HTML,而不是XML(我问这个问题的原因是HtmlAgilityParser不支持Android应用上的XPath,这正是我开发的目的,所以我正在尝试将我所有的XPath转换为LINQ)HtmlAgilityPack应该支持LINQ内置…非常感谢!这正是我所需要的。@user2396873:您正在使用HTML敏捷包吗?它没有与linqtoxml相同的api。
var table = doc.DocumentNode.Descendants("table")
    .Where(e => e.Attributes["border"] == "1")
    .First();
var rows = table.Descendants("tr")
    .Skip(1) // skip the first row
    .ToList();
var result = rows.Take(rows.Count - 1); // take all up to the last
.//div[span/@title='Event group']
var query =
    from d in e.Descendants("div")
    where d.Elements("span").Any(s => s.Attribute["title"] == "Event group")
    select d;