2014-06-05 90 views
-3

我試圖通過TD解析HTML文檔使用C# 標記,以便解析HTML行內文本

<td>Whatever string</td><td class="pass">value</td> 

將返回

Whatever string : value 

我已經在這個花了幾個小時問題,嘗試XML解析器和正則表達式,但無濟於事。謝謝你的幫助。

我已經嘗試

List<string> list = Regex.Split(lineslineWithTdTag[i], "[<td>].[<\td>]").ToList(); 
    List<string> status = Regex.Split(list[3], "[pass=\"].\"").ToList() ; 

,然後我試圖解析該列表

+1

你需要證明你已經嘗試任何代碼。 – Donal

+1

你試過了什麼?如果您發佈您正在使用的代碼,我們可以幫助解決問題。 –

+0

您是否嘗試過HtmlAgilityPack? –

回答

0

在招致較真的「與正則表達式不能解析HTML」的憤怒的風險,這裏有一個正則表達式解決方案應該做你想要什麼:

var match = Regex.Match(lineslineWithTdTag[I], "<td>(.*?)</td><td.*?>(.*?)</td>"); 
string result = String.Format(match.Groups[1].Value + " : " + match.Groups[2].Value); 

當然,如果實際記錄卻沒有得到很好格式化爲你的榜樣,那麼所有的賭注都關閉。

+0

http://stackoverflow.com/questions/1732348/regex-match-open -tags-except-xhtml-self-contained-tags#1732454 – Icemanind

+0

@icemanind - 是的,我在上面的評論中看到了這一點,並且熱愛這個答案。我同意正則表達式不能用於解析HTML。但是,對於可預見的HTML格式的可能的HTML情況的一個子集,它可能是有用的。 –

+0

真棒非常感謝你這真的幫助了一堆! – user3386190

0

了很多工作後,該結束了我的解決方案

 string path = @"http://localhost/page.html"; 
     XDocument myX = XDocument.Load(path); 
     string field1 = ""; 
     string field2 = ""; 
     bool flag = true; 
     foreach (var name in myX.Root.DescendantNodes().OfType<XElement>()) 
     { 
      // get the first element 
      if (name.Name.LocalName == "td" && flag) 
      { 
       field1 = (string)name + "\n"; 
       flag = false; 
      } 
      // get the second element 
      else if (name.Name.LocalName == "td") 
      { 
       field2 = (string)name + "\n"; 
       flag = true; 
      } 
     } 
    }