使用字符串中的标记循环浏览 HTML

本文关键字:循环 浏览 HTML 字符串 | 更新日期: 2023-09-27 18:37:18

由于性能原因,我正在将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部分。

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

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

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

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

使用字符串中的标记循环浏览 HTML

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

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

请以后自己谷歌搜索。