XPath节点选择

时间:2014-08-20 11:43:30

标签: parsing windows-phone-8 xpath html-agility-pack nodes

我正在使用HtmlAgilityPack来解析Windows Phone 8应用的数据。我管理了四个节点但是我在最后一个节点遇到了困难。

Game newGame = new Game();
newGame.Title = div.SelectSingleNode(".//section//h3").InnerText.Trim();
newGame.Cover = div.SelectSingleNode(".//section//img").Attributes["src"].Value;
newGame.Summary = div.SelectSingleNode(".//section//p").InnerText.Trim();
newGame.StoreLink = div.SelectSingleNode(".//img[@class= 'Store']").Attributes["src"].Value;
newGame.Logo = div.SelectSingleNode(".//div[@class= 'text-col'").FirstChild.Attributes["src"].Value;

最后一段代码是我遇到的问题。网站上的HTML看起来像这样(用我需要的数据简化)

<div id= "ContentBlockList" class="tier ">
   <section>
      <div class="left-side"><img src="newGame.Cover"></div>
      <div class="text-col">
         <img src="newGame.Logo http://url.png" />
         <h3>newGame.Title</h3>
         <p>new.Game.Summary</p>
         <a href="https://link to online store"><img src="newGame.StoreLink" class="Store" /></a>
      </div>
</div>
</section>

如您所见,我需要从这个HTML块中解析两个图像。这段代码似乎采用了第一个img src并正确地将它用于游戏封面......

newGame.Cover = div.SelectSingleNode(".//section//img").Attributes["src"].Value;

但是,我不知道如何让第二个img src检索商店Logo。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

newGame.Cover = div.SelectSingleNode(".//img[2]").Attributes["src"].Value;

你没有张贴整件事,但这应该可以解决问题。

答案 1 :(得分:0)

您可以尝试这种方式:

newGame.Cover = div.SelectSingleNode("(.//img)[2]")
                   .GetAttributeValue("src", "");

GetAttributeValue()优于Attributes["..."].Value,因为当后者抛出异常时,前一种方法会在找不到属性时返回第二个参数(上例中的空字符串)。

附注:您的HTML标记在发布时无效(某些元素未关闭,例如<section>)。这可能会引起混淆。