2012-11-18 61 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功能嗎? –

相關問題