使用 HtmlAgilityPack 处理嵌套元素

本文关键字:元素 嵌套 处理 HtmlAgilityPack 使用 | 更新日期: 2023-09-27 18:34:25

所以我正在尝试编写代码将HTML转换为Windows应用商店应用程序的Markdown。 到目前为止,我在HtmlAgilityPack上取得了很大的成功,但是我遇到了一个问题。

下面是一些示例 HTML

<p>A paragraph of text, including some text which is <strong>bolded</strong></p>
<p>Another paragraph</p>

我使用以下代码处理它。

foreach (var x in doc.Descendants.Where(x => x.Name == "p").ToList())
{
    x.ParentNode.ReplaceChild(
        HtmlAgilityPack.HtmlNode.CreateNode(x.InnerHtml 
            + Environment.NewLine 
            + Environment.NewLine),
        x);
}

预期输出为

A paragraph of text, including some text which is <strong>bolded</strong>
Another paragraph

但实际输出是

A paragraph of text, including some text which is 
Another paragraph

似乎一旦它到达嵌套节点,它就会忽略该点之后的所有内容。

如果我之前有处理strong标签的规则,那么输出是预期的。但是,我不能依靠"按顺序"做事,因为那样就没有办法处理诸如p之类的事情p

我做错了什么?

请注意,这适用于 Windows 应用商店应用,并使用不支持 XPath 的 HTMLAgilityPack 的 WinRT 版本

使用 HtmlAgilityPack 处理嵌套元素

CreateNode方法将仅从解析的 HTML 返回第一个同级。这就是为什么你不会得到粗体标签。因此,您必须找到所有兄弟姐妹并将它们插入回您的参数节点的位置并删除参数节点。

此代码可以帮助您入门:

foreach (var x in doc.DocumentNode.Descendants().Where(x => x.Name == "p").ToList())
{
    var node = HtmlNode.CreateNode(x.InnerHtml + Environment.NewLine + Environment.NewLine);
    foreach (var child in node.ParentNode.ChildNodes)
    {
        x.ParentNode.InsertBefore(child, x);
    }
    x.ParentNode.RemoveChild(x);
}
相关文章: