2017-08-08 87 views
0

我是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#中的實際行是什麼?因爲我看不到它是如何編譯的。 –

回答

0

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

如果它不包含撇號,或者將它們添加到變量或將它們添加到字符串:

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