在WP7中解析HTML字符串

本文关键字:HTML 字符串 WP7 | 更新日期: 2023-09-27 18:14:02

我需要解析从服务器接收到的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); 

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

在WP7中解析HTML字符串

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

你需要这样做:

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

使用 htmllagilitypack -不使用regex

Descendants中的'查询字符串'是XPath,而不是类似css的选择器。

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