我正在用 AngleSharp 编写一个 HTML 解析器,它应该像这样输入 HTML:
<p>
Paragraph Text
<a href="https://www.example com" class="external text" target="_new" rel="nofollow">Link Text</a>
Paragraph Text 2
</p>
并像这样输出:
<p>
Paragraph Text
<a href="https://www.example com">Link Text</a>
Paragraph Text 2
</p>
我编写了这个递归函数来遍历整个文档:
using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using AngleSharp.Extensions;
using AngleSharp.Parser.Html;
private void processHTMLNode(IElement node, IElement targetNode)
{
switch (node.NodeName.ToLower())
{
//...
case "a":
if(node.HasAttribute("href") && node.GetAttribute("href").StartsWith("#"))
{
break;
}
var aNew = outputDocument.CreateElement("a");
aNew.SetAttribute("href", node.GetAttribute("href"));
aNew.TextContent = node.TextContent;
targetNode.AppendChild(aNew);
break;
case "p":
var pNew = outputDocument.CreateElement<IHtmlParagraphElement>();
foreach (var childNode in node.Children)
{
processHTMLNode(childNode, pNew);
}
//TODO fix this
pNew.TextContent = node.TextContent;
targetNode.AppendChild(pNew);
break;
}
//...
}
问题是,设置TextContent
属性会覆盖作为 -Nodea
子级的p
-Elements。订单(文本->链接->文本)也丢失了。
我如何正确实施这一点?