【发布时间】:2012-03-08 17:38:54
【问题描述】:
我有以下节点
"/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[7]/p[1]/#text[1]"
我怎样才能确定其中最后一个是最接近的?
"/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[4]/div[1]/img[1]"
"/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[4]/div[3]/a[1]/img[1]"
"/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[4]/div[3]/a[2]/img[1]"
"/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[4]/div[5]/img[1]"
"/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[5]/div[1]/img[1]"
不一定是最后一个。
我是这样到达那里的:
protected string GuessThumbnail(HtmlDocument document)
{
HtmlNode root = document.DocumentNode;
IEnumerable<string> result = new List<string>();
HtmlNode description = root.SelectSingleNode(DescriptionPredictiveXPath);
if (description != null) // in this case, we predict relevant images are the ones closest to the description text node.
{
HtmlNode node = description.ParentNode;
while (node != null)
{
string path = string.Concat(node.XPath, ImageXPath);
node = node.ParentNode;
IEnumerable<HtmlNode> nodes = root.SelectNodesOrEmpty(path);
// find the image tag that's closest to the text node.
if (nodes.Any())
{
var xpaths = nodes.Select(n => n.XPath);
xpaths.ToList();
// return closest
}
}
}
// figure some other way to do it
throw new NotImplementedException();
}
【问题讨论】:
-
您的意思是在文档结构中与目标元素的距离最近吗?
-
是的,就是这样。我想以某种方式找出
div[7]更接近div[5]而不是div[4],如果有多个div[5],则检查下一级,等等。直到找到最接近的元素。 -
您的代码是否使用 CodePlex 的 Html Agility Pack?
-
另外,您需要排序的元素是否总是在同一级别具有相同的元素类型,即 div 到 div 等?问题是如果索引器不是,则您无法确定它们的接近程度,并且这消除了简单地比较 xpath 的能力。如果它们是不同的节点,那么区分的唯一方法是遍历树并记录每个发现的节点的距离度量。
标签: c# xpath html-agility-pack closest prediction