如何将变量插入xpath表达式语句C#?

问题描述:

我是Xpath表达式的新手,我有一些问题要问。如何将变量插入xpath表达式语句C#?

我想插入字符串selectedcountry到我的xpath表达式中,所以我尝试编码像这样,//a[contains(@href, "+selectedCountry+")]/text(),但收回了我想要的不正确的数据。

会话中的selectedCountry字符串是从用户中检索的,所以我确定里面的值是正确的。

当我改变到//a[contains(@href," "+selectedCountry+" ")]/text(),出现以下错误:

类型的异常“System.ArgumentNullException”发生在 System.Core.dll但在用户代码

附加没有处理信息:值不能为空。

情况1

string selectedCountry = Session["SelectedCountry"].ToString(); 

HtmlNode[] newnode = doc3.DocumentNode.SelectNodes("//a[contains(@href,'china')]/text()").ToArray(); 

结果:

中国支持联合能源开发与菲律宾在有争议的海上 中国敦促东盟拒绝外界干扰巴拿马切割台后打开使馆 在中国关系博茨瓦纳证实达赖喇嘛访问 尽管中国愤怒

情况2

string selectedCountry = Session["SelectedCountry"].ToString(); 

HtmlNode[] newnode = doc3.DocumentNode.SelectNodes("//a[contains(@href,"+selectedCountry+")]/text()").ToArray(); 

结果:

跳转到主要为首页亚洲 PacificSingaporeWorldCNA InsiderBusinessSportLifestyleTechnologyHealthCommentaryCatch升降电视

+0

当我更改为“//一个[含有(@ href,“”+ selectedCountry +“”)]/text()“,出现错误。 出现在C#中的实际行是什么?因为我看不到它是如何编译的。 –

如果"//a[contains(@href, 'china')]/text()"的作品,但"//a[contains(@href, "+selectedCountry+")]/text()"不,确保selectedCountry包含'china'包括撇号

如果它不包含撇号,或者将它们添加到变量或将它们添加到字符串:

"//a[contains(@href, '"+selectedCountry+"')]/text()"