【问题标题】:Loop through HTML with tags from string使用字符串中的标签循环遍历 HTML
【发布时间】:2013-11-07 03:31:24
【问题描述】:

由于性能原因,我正在将 PHP 脚本解析为 C#。

这是我遇到问题的 PHP 源代码:

$dom = new DOMDocument;
$dom->loadHTML($message);
foreach ($dom->getElementsByTagName('a') as $node) {
    if ($node->hasAttribute('href')) {
        $link = $node->getAttribute('href');
        if ((strpos($link, 'http://') === 0) || (strpos($link, 'https://') === 0)) {
            $add_key = ((strpos($link, '{key}') !== false) || (strpos($link, '%7Bkey%7D') !== false));
            $node->setAttribute('href', $url . 'index.php?route=ne/track/click&link=' . urlencode(base64_encode($link)) . '&uid={uid}&language=' . $data['language_code'] . ($add_key ? '&key={key}' : ''));
        }
    }
}

我遇到的问题是getElementByTagName 部分。

正如here 所说,我应该使用htmlagilitypack。到目前为止我的代码是这样的:

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(leMessage);

leMessage 是一个包含 HTML 的字符串。到目前为止,一切都很好。唯一的问题是 HtmlAgillityPack 中没有 getElementsByTag 函数。而在普通的 HtmlDocument(没有包)中,我不能使用字符串作为 html 页面,对吗?

那么有人知道我应该怎么做才能完成这项工作吗?我现在唯一能想到的就是在 windows 窗体中创建一个 webbrowser 并将文档内容设置为 leMessage 然后从那里解析它。但就我个人而言,我不喜欢那种解决方案……但如果没有其他方法……

【问题讨论】:

    标签: c# php html foreach getelementsbytagname


    【解决方案1】:

    以下是当我点击您的链接并单击“示例”时弹出的第一个页面顶部代码块:

     HtmlDocument doc = new HtmlDocument();
     doc.Load("file.htm");
     foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])
     {
        HtmlAttribute att = link["href"];
        // DO SOMETHING WITH THE LINK HERE
     }
     doc.Save("file.htm");
    

    以后请自行搜索。

    【讨论】:

    • 哇,我没看到。我很抱歉。但无论如何,谢谢你花时间告诉我:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 2016-01-24
    • 2019-06-24
    相关资源
    最近更新 更多