【发布时间】:2019-10-11 14:19:42
【问题描述】:
要求: 在字符串中的 body 标记后添加自定义 html
我用 htmlagilitypack 解决了这样的问题:
StringBuilder sb = new StringBuilder();
sb.Append(customStringWithHtmlContent)
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(sb.ToString());
// Create new node from newcontent
HtmlNode newNode = HtmlNode.CreateNode("<div>" + someStringWithAdditionalContent + "</div>");
// Get body node
HtmlNode body = htmlDoc.DocumentNode.SelectSingleNode("//body");
if (body != null)
{// Add new node as first child of body
body.PrependChild(newNode);
}
var docContent = htmlDoc.DocumentNode.InnerHtml;
看起来不错,但在某些 html 页面中,html 结构发生了变化,封闭的 div 标签被移动,html 呈现丑陋
第二种解决方案:
if (sb.ToString().Contains("<body>"))
{
sb.Replace("<body>", "<body><div>" + someStringWithAdditionalContent + "</div>");
}
看起来不错,但不是具有类似属性的 body 的解决方案
<body style="someAttr:value ..." ...>
一些想法?其他解决方案?
【问题讨论】:
-
您的第一个解决方案看起来不错。您是否有一个无法使用的 HTML 示例?
标签: c# html html-agility-pack