2010-10-23 109 views
0

我正在寻找解析我的应用程序的一些信息。 比方说,我们在该字符串的地方:解析大字符串(HTML代码)

<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

正如你可能猜到我完全不知道如何做到这一点...我知道我可以执行的字符串(拆分等)帮助的任何功能。

在此先感谢

+0

等待暗示正则表达式 – JustSid 2010-10-23 19:33:14

+0

@JustSid那些你会用什么其他这将使它容易。你也可以使用jquery获取值,并做你需要做的事情。我想这真的只取决于他想要完成什么 – Matt 2010-10-23 19:41:26

回答

1

只需使用String.IndexOf(字符串,整数)找到一个 “< TD”,再寻找下一个 “>”,并再次找到 “</TD >”。然后使用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); 
    } 
+0

一个非常好的答案,容易理解。 – Qosmo 2010-10-23 20:32:40

+0

..谢谢! .. – arx 2010-10-23 20:40:07

0

假设你的字符串是有效的XHTML,你可以使用使用XML解析器来获得你想要的内容。有一个simple example here,显示如何使用XmlTextReader解析XML内容。这个例子从文件中读取,但你可以改变它从一个字符串读取:

new XmlTextReader(new StringReader(someString)); 

您明确要保持td元素节点的轨道,并且它们后面的文本节点将包含您想要的值。

0
  • 使用一个循环来从所述文件中的每个非空行加载到一个字符串
  • 过程由字符的字符串字符
    • 检查用于指示td标签的开始时的字符
    • 使用子字符串函数或只是逐个字符地构建一个新字符串以获取所有内容,直到</td>标记开始。