Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.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
.net Html Agility Pack返回无效的XPath_.net_Xpath_Html Agility Pack - Fatal编程技术网

.net Html Agility Pack返回无效的XPath

.net Html Agility Pack返回无效的XPath,.net,xpath,html-agility-pack,.net,Xpath,Html Agility Pack,我在两个窗口中打开了一个HTML文档,我需要在两个窗口之间同步所选节点 使用我尝试过的: 异常消息:“/#注释[1]”具有无效令牌。 我想知道,我从节点本身获取了XPath,这意味着它是一个正确的XPath,我对同一个文档使用它,为什么失败,我遗漏了什么 更新 当选择一些其他节点时,我得到了这个异常:表达式必须计算为一个节点集。(xpath包含/html[1]/body[1]/div[1]/p[3]/strong[1]/#text[1]) 但是请记住,该值是从节点本身获取的,因此非常奇怪。它为什

我在两个窗口中打开了一个HTML文档,我需要在两个窗口之间同步所选节点

使用我尝试过的:

异常消息:
“/#注释[1]”具有无效令牌。

我想知道,我从节点本身获取了XPath,这意味着它是一个正确的XPath,我对同一个文档使用它,为什么失败,我遗漏了什么

更新

当选择一些其他节点时,我得到了这个异常:
表达式必须计算为一个节点集。
xpath
包含
/html[1]/body[1]/div[1]/p[3]/strong[1]/#text[1]


但是请记住,该值是从节点本身获取的,因此非常奇怪。它为什么抱怨它无效?

元素名中的#字符是非法的。选择注释的有效XPath表达式应该是
/comment()[1]

,根据Mak Toro的回答,我创建了一个变通函数:

private string ValidateXPath(string xpath)
{
  var index = xpath.LastIndexOf("/");
  var lastPath = xpath.Substring(index);

  if (lastPath.Contains("#"))
  {
    xpath = xpath.Substring(0, index);
    lastPath = lastPath.Replace("#", "");
    lastPath = lastPath.Replace("[", "()[");
    xpath = xpath + lastPath;
  }                                

  return xpath;
}

现在它工作得很好。

那么它是如何由HtmlNode.XPath属性返回的呢??有没有办法将HtmlNode.XPath转换为有效的XPath?@Shimmy:你必须询问该库的开发人员。我知道这是一篇老文章,但我建议只使用
XPath.Replace(“#comment”,“comment()”)看起来你的方法有很多地方可能会出错。
private string ValidateXPath(string xpath)
{
  var index = xpath.LastIndexOf("/");
  var lastPath = xpath.Substring(index);

  if (lastPath.Contains("#"))
  {
    xpath = xpath.Substring(0, index);
    lastPath = lastPath.Replace("#", "");
    lastPath = lastPath.Replace("[", "()[");
    xpath = xpath + lastPath;
  }                                

  return xpath;
}