【问题标题】:Add div in HTML after <body ...> in c#在 c# 中的 <body ...> 之后在 HTML 中添加 div
【发布时间】: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


【解决方案1】:

正则表达式?可能有一种更优雅的方式,但基本思想是:

    string input = "<body style=\"someAttr\"><tag>sdsdsa</tag></body>";
    Regex Pattern = new Regex(@"(<body.*?>)(.*?)(<\/body>)", RegexOptions.Compiled);

    var updatedText = Pattern.Replace(input, match =>
    {
        string newMatch = match.Groups[2].Value;
        string newContent = "<div>" + "someStringWithAdditionalContent" + "</div>";
        return match.Groups[1].Value + newContent + newMatch + match.Groups[3].Value;
    });
    Console.WriteLine(updatedText);

输出:

<body style="someAttr"><div>someStringWithAdditionalContent</div><tag>sdsdsa</tag></body>

【讨论】:

    猜你喜欢
    • 2016-01-22
    • 2020-12-26
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 2019-01-08
    相关资源
    最近更新 更多