解析大字符串(HTML code)

时间:2010-10-23 19:31:01

标签: c# string parsing

我正在寻找解析有关我的申请的一些信息。 假设我们在该字符串中有某处:

<tr class="tablelist_bg1">

<td>Beja</td>

<td class="text_center">---</td>

<td class="text_center">19.1</td>

<td class="text_center">10.8</td>

<td class="text_center">NW</td>

<td class="text_center">50.9</td>

<td class="text_center">0</td>

<td class="text_center">1016.6</td>

<td class="text_center">---</td>

<td class="text_center">---</td>

</tr>

所有高于或低于此值的休息并不重要。记住这都在一个字符串里面。 我想得到td标签内的值:---,19.1,10.8等。 值得知道,页面上有很多这样的条目。 link the page here可能也是一个好主意。

你可能已经猜到我完全不知道如何做到这一点......我所知道的任何功能都不能通过字符串(拆分等)帮助。

提前致谢

3 个答案:

答案 0 :(得分:1)

只需使用String.IndexOf(string,int)查找“&lt; td”,再次找到下一个“&gt;”,再次找到“&lt; / td&gt;”。然后使用String.Substring来提取一个值。把它放在一个循环中。

    public static List<string> ParseTds(string input)
    {
        List<string> results = new List<string>();

        int index = 0;

        while (true)
        {
            string next = ParseTd(input, ref index);

            if (next == null)
                return results;

            results.Add(next);
        }
    }

    private static string ParseTd(string input, ref int index)
    {
        int tdIndex = input.IndexOf("<td", index);
        if (tdIndex == -1)
            return null;
        int gtIndex = input.IndexOf(">", tdIndex);
        if (gtIndex == -1)
            return null;
        int endIndex = input.IndexOf("</td>", gtIndex);
        if (endIndex == -1)
            return null;

        index = endIndex;

        return input.Substring(gtIndex + 1, endIndex - gtIndex - 1);
    }

答案 1 :(得分:0)

假设您的字符串是有效的XHTML,您可以使用XML解析器来获取所需的内容。有一个simple example here显示了如何使用XmlTextReader来解析XML内容。该示例从文件中读取,但您可以将其更改为从字符串中读取:

new XmlTextReader(new StringReader(someString));

您特别希望跟踪td个元素节点,其后面的文本节点将包含您想要的值。

答案 2 :(得分:0)

  • 使用循环将文件中的每个非空行加载到String
  • 逐个字符处理字符串
    • 检查表明td标签开头的字符
    • 使用子字符串函数或者只是按字符逐行添加新字符串以获取所有内容,直到</td>标记开始。