c# - 使用 html 敏捷包从 c# 中的 html 中提取图像 url 并将它们写入 xml 文件

标签 c# html-agility-pack xml

我是 c# 的新手,我真的需要帮助解决以下问题。我希望从具有特定模式的网页中提取照片网址。例如,我希望提取所有具有以下模式 name_412s.jpg 的图像。我使用以下代码从 html 中提取图像,但我不知道如何调整它。

public void Images()
    {
        WebClient x = new WebClient();
        string source = x.DownloadString(@"http://www.google.com");

        HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
        document.Load(source);

        foreach(HtmlNode link in document.DocumentElement.SelectNodes("//img")
        {
          images[] = link["src"];
       }
}

我还需要将结果写入 xml 文件中。你也可以帮我吗?

谢谢!

最佳答案

要限制查询结果,您需要在 XPath 中添加一个条件。例如,//img[contains(@src, 'name_412s.jpg')]将结果限制为仅 img具有 src 的元素包含该文件名的属性。

就将结果写出到 XML 而言,您需要创建一个新的 XML 文档,然后将匹配的元素复制到其中。由于您无法将 HtmlAgilityPack 节点直接导入到 XmlDocument 中,因此您必须手动复制所有属性。例如:

using System.Net;
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);
    }
    output.Save(@"C:\test.xml");
}

关于c# - 使用 html 敏捷包从 c# 中的 html 中提取图像 url 并将它们写入 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13435508/

相关文章:

c# - 如何在 C# 中创建 JSON 对象

asp.net - Htmlagilitypack 获取外部元素

c# - 无法在 VS2012 上安装 HtmlAgilityPack

javascript - 使用 jQuery 访问 XML 值

css - 指定一个元素显示为图片

c# - 在 C# 中设置秒表程序的开始时间

c# - 使用 C# MVC4 并将 DbContext 类名称与 ConnectionString 名称匹配以使用正确的数据库?

c# - WAV记录器功能,需要将格式更改为int16或int24

C# 如何使用 LINQ 获取特定列标题名称下的所有单元格数据

java - 如何将值从portal-ext.properties传递到ilferay-portlet.xml文件?