2014-09-20 196 views
0

我有一个网页,这样其在li标签从HTML标签中提取文本

<li>nafiz</li> 
<li>ACE</li> 
<li>Sanah</li> 

3倍的值和该代码给了我只有最后的innerText:

public string names = ""; 
    public string names2 = ""; 
    public string names3 = ""; 


    // Use this for initialization 
    void Start() { 

     HtmlWeb hw = new HtmlWeb(); 
     HtmlAgilityPack.HtmlDocument doc = hw.Load(openUrl); 

    foreach (HtmlNode nd in doc.DocumentNode.SelectNodes("//li")) 
     { 
      names=nd.InnerText.ToString(); 

     } 

我怎么能存储所有这些字符串中有3个值?

回答

1

会更容易:

var names = new List<string>(); 
..... 
..... 
foreach (HtmlNode nd in doc.DocumentNode.SelectNodes("//li")) 
{ 
    names.Add(nd.InnerText.Trim()); 
} 

InnerText已属于string无需额外加入ToString()。在上面的例子中,Trim()意味着从前导空白和尾随空白处清除name

+0

非常感谢...它的工作 – NafizImtiaz 2014-09-20 07:47:37

1

您可以使用此功能

string[] GetItems(string htmlText) 
    { 
     List<string> Answer = new List<string>(); 
     for (int i = 0; i < htmlText.Length; i++) 
     { 
      int start = htmlText.IndexOf('>', i); 
      i = start; 
      int end = htmlText.IndexOf('<', i); 

      if (end == -1 || start == -1) 
       break; 

      string Item = htmlText.Substring(start + 1, end - start - 1); 
      if (Item.Trim() != "") 
       Answer.Add(Item); 

      i = end + 1; 
     } 
     return Answer.ToArray(); 
    } 

,并用它......如果你存储在字符串数组或列表中的3个值,例如

 foreach (string item in GetItems(YourText)) 
    { 
      MessageBox.Show(item); 
    }