【问题标题】:Parsing HTML string in WP7在 WP7 中解析 HTML 字符串
【发布时间】:2011-11-08 10:57:43
【问题描述】:

我需要解析从服务器接收到的 HTML 字符串。

 <html>
 <head/>
 <body style="margin: 0;padding: 0">
    <a href="http://itunes.apple.com/WebObjects/MZStore.woa   
/wa/viewSoftware?id=319737742&amp;mt=8&amp;uo=6" style="margin: 0;padding: 0"><img   
src="https://s3.amazonaws.com/sportschatter/postcard.jpg" style="margin: 0;padding: 
0"/></a>
</body>
</html>

这是我从服务器得到的响应。我需要检索img URL https://s3.amazonaws.com/sportschatter/postcard.jpg 以及href 部分。 我有 WP7 的 HTML 敏捷包,但我不知道如何编写查询来获取此信息。我尝试过这样的事情:

HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
         document.LoadHtml(htmlString);


       var value  =  document.DocumentNode.Descendants("img src").
                                       Select(
                                           x =>
                                           x.InnerText);

这没有给我任何价值。我也试过Regex

    string parseString = htmlstring;
        Regex expression = new Regex(@".*img src=(\d+).*$");
        Match match = expression.Match(parseString);
        MessageBox.Show(match.Groups[1].Value); 

但这也不起作用。请让我知道我做错了什么。

【问题讨论】:

  • 我也看过很多 html Agility 的例子,其中大多数使用 SelectNodes 方法,该方法在库的 WP7 版本中不存在

标签: c# windows-phone-7 html-parsing


【解决方案1】:

您显然误解了您应该如何使用 LINQ2XML 语法(没有 XPath,因为 Windows Phone 不支持 XPath)

你需要这样做:

var image = document.DocumentNode.Descendants("img").First()
var source = image.GetAttribute("src", "").Value;

【讨论】:

  • 感谢它的工作,我必须稍微改变一下 var image = document.DocumentNode.Descendants("img").First(); var source = image.GetAttributeValue("src", "");我如何获取通常在 p 标签中的文本值
  • 使用InnerHtmlInnerText 属性。
【解决方案2】:

使用 HtmlAgilityPack - 不要使用正则表达式。

Descendants 中的“查询字符串”是一个 XPath,而不是类似 CSS 的选择器。

这是一个例子:http://htmlagilitypack.codeplex.com/wikipage?title=Examples 以下是有关 XPath 的一些信息:http://msdn.microsoft.com/en-us/library/ms256086.aspx

【讨论】:

  • HI Jakub,示例链接使用 doc.DocumentElement.SelectNodes,我使用 HAPPhone 版本的 htmlAgility 包,它没有 DocumnentElemnt 方法。
  • XPath 在 Windows Phone 上不受支持。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-27
  • 2012-08-29
  • 1970-01-01
  • 2011-04-05
  • 2010-12-02
  • 2012-05-31
  • 1970-01-01
相关资源
最近更新 更多