Reputation: 43
I have a page like this which has 3 values in li
tags
<li>nafiz</li>
<li>ACE</li>
<li>Sanah</li>
And this code gives me only the last 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();
}
How can I store all 3 values in those strings?
Upvotes: 0
Views: 91
Reputation: 89335
Will be easier if you store the 3 values in string array or list, for example :
var names = new List<string>();
.....
.....
foreach (HtmlNode nd in doc.DocumentNode.SelectNodes("//li"))
{
names.Add(nd.InnerText.Trim());
}
InnerText
is already of type string
no need to put additional ToString()
. Trim()
in above example meant to clear the name
from leading and trailing white-spaces.
Upvotes: 1
Reputation: 2812
you can use this function
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();
}
and use it...
foreach (string item in GetItems(YourText))
{
MessageBox.Show(item);
}
Upvotes: 1