2015-11-15 125 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