【问题标题】:How to use Html Agility Pack with windows 8 apps?如何在 Windows 8 应用程序中使用 Html Agility Pack?
【发布时间】:2012-11-18 15:41:33
【问题描述】:

首先我想说我是 C# 和 Windows 8 应用程序的新手。所以,请不要对我太苛刻。

我有以下代码来提取一些图像 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");
}

你能帮帮我吗?

谢谢!

【问题讨论】:

    标签: c# xml windows-8 html-agility-pack


    【解决方案1】:
    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;
    

    【讨论】:

    • 我不得不改变 out.Save 到 outline.Save 。 WebClient 在 Windows 8 应用程序中无法识别,因此我使用 HttpClient 对其进行了更改,但现在 DownloadString 不再工作了。我想我必须用 client.GetAsync 来改变它。我还必须用 DocumentNode 更改 DocumentElement。你能帮我使用 GetAsync 功能吗?
    【解决方案2】:

    试试这样的:

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      相关资源
      最近更新 更多