【问题标题】:Insert into string after nth occurrence of token在第 n 次出现标记后插入字符串
【发布时间】:2017-11-28 11:42:15
【问题描述】:

我在字符串变量 myHtml 中有以下 HTML。myHTML 变量填充了来自某个函数的 HTML,该函数返回 HTML 如下

string myHtml="<table> <tr id='12345'><td>Hello1</td></tr> <tr id='12346'><td>Hello2</td></tr> </table>";

在这个例子中,我返回的数据中有两行,我需要在上面的行之间添加另一行id=1234678。那么myHtml 可能看起来像

myHtml="<table> <tr id='12345'><td>Hello1</td></tr> <tr id='1234678'><td>Hello New</td></tr>  <tr id='12346'><td>Hello2</td></tr> </table>";

我想通过在 indexOf 等字符串操作的帮助下附加 HTML 来做到这一点,但我不知道如何做到这一点。

【问题讨论】:

  • 我想用 indexOf 做一些事情,方法是获取带有 orderid 的 tr 标签,但没有成功
  • 使用子字符串。将字符串拆分成碎片,在里面添加一些东西然后加入。我说的对吗?
  • @asawyer,嗯,第 2 位。Jeff Atwood 认为 70%“相当好”,所以大概 67% 相当好 - blog.stackoverflow.com/2009/08/new-question-asker-features
  • 为什么不使用 XML 方法?为什么要使用 indexOf 之类的字符串操作?
  • @dsolimano Gotcha,我会记住这一点。对不起阿巴斯!嗯,我的其他评论去哪儿了?很奇怪。

标签: c# html string


【解决方案1】:

不要为此使用字符串,而是为此使用库。例如HTML agility pack

【讨论】:

  • 为什么不呢? HTML 敏捷包是实现您想要的最佳方式。
  • 因为我不能看别的东西。
【解决方案2】:

总是只有 2 行吗?如果是这样,这将起作用:

string newRow = " <tr id='1234678'><td>Hello New</td></tr> ";
int i = myHtml.IndexOf("</tr>") + 5;            
string newHtml = myHtml.Insert(i, newRow);

如果可以有任意数量的行,我们需要编写一个方法来查找要插入的特定索引。

例如:

    int IndexOfNth(string source, string token, int nTh)
    {
        int index = source.IndexOf(token);

        if (index != -1)
        {
            int i = 1;
            while (i++ < nTh)
                index = source.IndexOf(token, index + 1);
        }

        return index;
    }

然后你会使用:

int i = IndexOfNth(myHtml, "</tr>", 1) + 5; // find first "</tr>" and insert after

// Or you could use
int i = IndexOfNth(myHtml, "<tr ", 2); // find second "<tr " and insert before

【讨论】:

  • 我想在具有特定 ID 的行之前插入...这是否适用于特定 ID...并且可以有无限行
  • 要在特定 id 之前插入,您可以使用例如IndexOfNth(myHtml, "&lt;tr id='12346'&gt;", 1) 但如果 id 是唯一的,那么您可以使用 myHtml.IndexOf("&lt;tr id='12346'&gt;") 因为它总是第一次出现。
  • 但是你真的必须小心这个,因为如果 HTML 的格式不完美,它可能会损坏。 (这就是为什么你应该使用适当的 HTML 操作库)。
【解决方案3】:

试试这个

    myHtml = "<table> <tr id='12345'><td>Hello1</td></tr> <tr id='12346'><td>Hello2</td></tr> </table>";
    int index1 = myHtml.IndexOf("<tr", 0);
    int index2 = myHtml.IndexOf("<tr", index1 + 3); // 3 for amount of characters in '<tr'
    myHtml = myHtml.Insert(index2, "<tr id='1234678'><td>Hello</td></tr>");

您还可以通过循环构建一个数组,这样如果现有行多于两行,您就可以在任意位置插入该行。

【讨论】:

  • 3 是什么意思...你能解释一下吗??
  • 的索引将返回第一个左括号“
【解决方案4】:

尝试使用 Linq to XML。根据您的字符串创建一个 XDocument。然后搜索你的 tr 节点并插入你的新 tr 节点。

var newTR = new XElement("tr", new XAttribute("id", "1234678"), new XElement("td", "Hello3"));
TextReader tr = new StringReader(myHtml);
XDocument doc = XDocument.Load(tr);
doc.Decendants().Skip(1).AddAfterSelf(newTR);
var newStr = doc.ToString();

【讨论】:

    猜你喜欢
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 2011-07-26
    • 2016-08-04
    • 2019-01-31
    • 2021-02-10
    相关资源
    最近更新 更多