2012-11-18 31 views
1

首先,我想说,我是c#和Windows 8应用程序的新手。所以,请不要对我很难。如何在Windows 8应用程序中使用Html Agility Pack?

我有下面的代码中提取一些图像的URL,并将它们保存在一个XML文件中。 我使用的是Html Agility Pack,但是当我尝试在Windows 8应用程序中使用代码时,它不起作用。我知道我必须从这里使用Fizzler Html Agility Pack:http://fizzlerex.codeplex.com/releases/view/89833但我不知道什么是错的。 我使用的Visual Studio 2012和它不承认下列元素:

***WebClient*** x = new ***WebClient***(); 
***XmlDocument*** output = new ***XmlDocument***(); 
***XmlElement*** imgElements = output.CreateElement("ImgElements"); 
foreach(HtmlNode link in document.***DocumentElement***.SelectNodes("//img[contains(@src, '_412s.jpg')]"));            
***out***.Save(@"C:\test.xml"); 

代码:

using HtmlAgilityPack; 
using Fizzler; 
using Fizzler.Systems.HtmlAgilityPack; 
using System.Xml; 

public void Images() 
{ 
    WebClient x = new WebClient(); 
    string source = x.DownloadString(@"http://www.google.com"); 
    HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); 
    document.Load(source); 
    XmlDocument output = new XmlDocument(); 
    XmlElement imgElements = output.CreateElement("ImgElements"); 
    output.AppendChild(imgElements); 
    foreach(HtmlNode link in document.DocumentElement.SelectNodes("//img[contains(@src, '_412s.jpg')]")) 
    { 
     XmlElement img = output.CreateElement(link.Name); 
     foreach(HtmlAttribute a in link.Attributes) 
     { 
      img.SetAttribute(a.Name, a.Value); 
     } 
     imgElements.AppendChild(img); 
    } 
    out.Save(@"C:\test.xml"); 
} 

你能帮帮我吗?

谢谢!

回答

0

尝试这样:

HttpClientHandler handler = new HttpClientHandler(); 
HttpClient client = new HttpClient(handler as HttpMessageHandler) { BaseAddress = new Uri(@"http://www.google.com") }; 
var r = await client.GetAsync(client.BaseAddress); 
string html; 
if (r.IsSuccessStatusCode) html = await r.Content.ReadAsStringAsync(); 
2
out.Save(@"C:\test.xml"); 

应该是:

output.Save(@"C:\test.xml"); 

然后你需要添加下面两个命名空间,则代码文件的顶部:

using System.Xml; 
using System.Net; 

这些错误无关的Windows 8.任何版本都会出现错误。我不确定为什么你需要从WebClient类转换到HttpClient类,因为它们在Windows 8中都受支持,但是,如果要使用HttpClient类,则应该这样工作:

HttpClient x = new HttpClient(); 
Task<string> t = x.GetStringAsync(@"http://www.google.com"); 
t.Wait(); 
string source = t.Result; 
+0

我不得不out.Save改为outline.Save。 WebClient在Windows 8应用程序中无法识别,因此我使用HttpClient对其进行了更改,但现在DownloadString不再工作。我想我必须改变它与client.GetAsync。我还必须使用DocumentNode更改DocumentElement。你能帮我使用GetAsync功能吗? –

相关问题