在c#中在[]之后在HTML中添加div 要求:在字符串的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 style="someAttr:value ..." ...> 一些想法?其他解决方案? 要求:在字符串中的body标记后添加自定义html,我用htmlagilitypack这样解决:StringBuilder sb = new StringBuilder(); sb.Append(customStringWithHtmlContent)HtmlDocument ... RegEx?可能还有一种更优雅的方式,但基本思想: 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>

问题描述 投票:0回答:1

要求:在字符串的body标记后添加自定义html]

我用htmlagilitypack这样解决:

c# html html-agility-pack
1个回答
0
投票

RegEx?可能还有一种更优雅的方式,但基本思想:

© www.soinside.com 2019 - 2024. All rights reserved.