如何将变量插入到 html 字符串中,以确保它不会使用 c# 插入到元素中

  • 本文关键字:插入 元素 确保 变量 html 字符串 c#
  • 更新时间 :
  • 英文 :


我正试图在特定索引处将特定变量插入HTML字符串中(这可能会随着HTML字符串的变化而变化(。

我遇到的问题是,有时索引在html元素中。

解决这个问题的最佳方法是什么?

public static string AppendStringWithReadMoreFlag(string htmlString, int readMoreCount)
{
string readMoreFlag = "<!--pagebreak-->";
var html = new HtmlAgilityPack.HtmlDocument();
html.LoadHtml(htmlString);
int length = html.DocumentNode.InnerText.Length;
if (length > readMoreCount)
{
// check if index is in a an html element
// perhaps check if > is before < else move to the index after > ?
htmlString = htmlString.Insert(readMoreCount, readMoreFlag);
}
return htmlString;
}

您可以尝试在要插入的位置之后找到第一个<>,这样您就可以知道是否在元素内部插入,然后可以使用它来更正索引。参见以下代码:

// get indexes of < and > after place you want to insert
var idx1 = html.DocumentNode.InnerText.IndexOf('<', readMoreCount + 1);
var idx2 = html.DocumentNode.InnerText.IndexOf('>', readMoreCount + 1);
// determine which is first: one that closes element, or one that open
if(idx2 < idx1)
// In that case we wil put text right after element is closed with ">"
readMoreCount = idx2 + 1;

最新更新