如何获得第二个标签值

时间:2016-03-29 14:04:25

标签: c# html

我有以下代码,但我想要第二个td值怎么做?请帮忙。

string value = getBetween(xml, "<td class=\"statusValue\">", "</td>");

public static string getBetween(string strSource, string strStart, string strEnd)
{
    int Start, End;
    if (strSource.Contains(strStart) && strSource.Contains(strEnd))
    {
        Start = strSource.IndexOf(strStart, 0) + strStart.Length;
        End = strSource.IndexOf(strEnd, Start);
        return strSource.Substring(Start, End - Start);
    }
    else
    {
        return "";
    }
}

请参见下图。enter image description here

1 个答案:

答案 0 :(得分:1)

您还可以使用Regex获取所有匹配项:

public static string getBetween(string strSource, string strStart, string strEnd)
{
    string pattern = string.Format("{0}((.|\n|\r)*?){1}", strStart, strEnd);
    Regex r = new Regex(pattern);
    var matchCollection = r.Matches(strSource);
    //you can iterate through collection

    foreach (Match match in r.Matches(strSource))
    {

        string textBetweenTags = match.Groups[1].ToString();
        //your logic here
    }

    //or return second value you want
    if (matchCollection.Count >= 2)
    {
        return matchCollection[1].Groups[1].ToString();
    }
    else
    {
        return "";
    }
}