【问题标题】:Add </LI> closing tags to each REGEX match in string将 </LI> 结束标记添加到字符串中的每个 REGEX 匹配项
【发布时间】:2012-07-27 15:20:21
【问题描述】:

我有一个带有未封闭 &lt;LI&gt; 元素的 HTML 文档。我需要将&lt;/LI&gt; 附加到每个&lt;/OBJECT&gt; 的末尾,然后是打开&lt;LI&gt; 标记。 注意: 前面没有&lt;LI&gt; 的对象不应在&lt;/OBJECT&gt; 后面附加&lt;/LI&gt; 标签

<OBJECT value="example">
    <param name="Joe">

    </OBJECT>
<UL>
    <LI> <OBJECT type="example">
        <param name="Pat">
        <param name="State" value="Arizona">
        </OBJECT>
    <UL>
        <LI> <OBJECT type="example">
            <param name="Steve">
            <param name="State" value="California">
            </OBJECT>

<OBJECT type="text/sitemap">
    <param name="Carol">

    </OBJECT>

这是我到目前为止没有运气的结果

private void closeListItems(string doc)
{
    StringBuilder sb = new StringBuilder();
    Regex rx = new Regex("(<LI>.(.+?)</OBJECT>)", RegexOptions.Multiline | RegexOptions.IgnoreCase);
    string[] hhcFile = File.ReadAllLines(doc);
    string temp = "";
    foreach (string line in hhcFile)
    {
        temp += line + "\n";
    }
    temp = rx.Replace(temp, "<LI>");
    StreamWriter sw = new StreamWriter(Application.StartupPath + "\\liFix.txt");
    sw.Write(temp);
    sw.Close();

}

更新:我也试过了,但没有运气:

private void closeListItems(string doc)
{
    StringBuilder sb = new StringBuilder();
    string[] hhcFile = File.ReadAllLines(doc);
    string temp = "";
    bool liOpen = false;
    foreach (string line in hhcFile)
    {
        temp = line;
        if (line.Contains("<LI>"))
        {
            liOpen = true;
        }
        if (line.Contains("</OBJECT>") && liOpen == true)
        {
            temp.Replace(temp, temp + "</LI>");
            liOpen = false;
        }
        sb.Append("\n" + temp);
    }
    File.WriteAllText("fixLi.txt", sb.ToString());

}

【问题讨论】:

  • 我有一个 HTML 文档,其中包含未封闭的 &lt;LI&gt; 元素。 — 不,你没有。 li 元素的结束标记在 HTML 中是可选的,因此它们是封闭的(只是没有明确地)。
  • 这是有效的 HTML,结束 &lt;/li&gt; 是可选的。为什么需要这样做?
  • HtmlAgilityPack 无法正确解析未关闭的 LI 标记(尽管我努力通过源代码重新编译 HAP 并进行修改以修复它)。
  • 标签区分我需要使用 XPATH 解析的两种类型的对象。
  • @Quentin "...解析有限的已知 HTML 集有时是合适的。"
  • 标签: c# html regex string


    【解决方案1】:

    这个答案只是根据你的更新:

    string.Replace 返回一个字符串。字符串在 C# 中是不可变的,这意味着您不能直接更改字符串。任何看似更改字符串的操作实际上都返回一个。

    因此,这一行:

    temp.Replace(temp, temp + "</LI>");
    

    ..什么都不做。应该是:

    temp = temp.Replace(temp, temp + "</LI>");
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签