2015-11-15 124 views
0

我試圖檢查這個網站上的其他答案,但他們都沒有爲我工作。我有以下HTML代碼:如何從XPATH獲取URL?

<h3 class="x-large lheight20 margintop5"> 
    <a href="http://someUrl.com" class="marginright5 link linkWithHash detailsLink"><strong>some textstring</strong></a> 
</h3> 

我想從這個文件得到與下面的代碼:

string adUrl = Doc.DocumentNode.SelectSingleNode("//*[@id=\"offers_table\"]/tbody/tr["+i+ "]/td/table/tbody/tr[1]/td[2]/div/h3/a/@href").InnerText; 

我也想這樣做沒有@href。還試用a[contains(@href, 'searchString')]。但所有這些行給我的鏈接的名稱 - 一些文本字符串

+0

InnerText?你爲什麼試圖使用它,而不是獲取屬性(這是什麼'href'是?像http://stackoverflow.com/questions/3750678/getting-attribute-value-of-an-xml-document-using-c -sharp –

回答

3

屬性沒有InnerText。您必須改用Attributes集合。

string adUrl = Doc.DocumentNode.SelectSingleNode("//*[@id=\"offers_table\"]/tbody/tr["+i+ "]/td/table/tbody/tr[1]/td[2]/div/h3/a") 
           .Attributes["href"].Value; 
1

爲什麼不只是使用XDocument類?

private string GetUrl(string filename) 
{ 
    var doc = XDocument.Load(filename) 
    foreach (var h3Element in doc.Elements("h3").Where(e => e.Attribute("class")) 
    { 
     var classAtt = h3Element.Attribute("class"); 
     if (classAtt == "x-large lheight20 margintop5") 
     { 
      h3Element.Element("a").Attribute("href").value; 
     } 
    } 
} 

該代碼未經過測試,因此請謹慎使用。

+0

Html的格式不如xml。這就是爲什麼我們有像html敏捷包這樣的庫,它可以很好地處理malformmatted html。 –

+0

是的,我知道,但我只是根據提供的示例回答。 – CodingMadeEasy