1

<LI>我有一个带有未封闭元素的 HTML 文档。我需要附加</LI>到每个</OBJECT>开头<LI>标签后面的末尾。 注意:前面没有的对象<LI>不应</LI>附加标签</OBJECT>

<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());

}
4

1 回答 1

2

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

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

因此,这一行:

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

..什么也没做。它应该是:

temp = temp.Replace(temp, temp + "</LI>");
于 2012-07-29T22:31:02.000 回答