2010-10-23 113 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>標記開始。