This question is a follow on from an earlier question I posted here about parsing HTML Read HTML on Windows Phone 8
I am parsing a HTML page that has a ton of tr tags like this:
<tr>
<td class="first">
</td>
<td >
Origin
</td>
<td>
Airline
</td>
<td>
Flight Number
</td>
<td>
22 Feb 11:50
</td>
<td class="last">
Arrived 12:35
</td>
</tr>
This is the code I am using to read the page and it's working fine:
foreach (HtmlNode node in htmlDocument.DocumentNode.SelectNodes("//td"))
{
string item = node.ChildNodes[0].InnerHtml.Trim();
lstResults.Items.Add(item)
}
The problem is, I want to concatenate each group of 5 TD values into one string. At the moment, the code is adding each item individually into the lisbox, so I basically get 5 entries per flight like this:
FlightNumber
DueTime
arrival time
Origin
Airline
But instead I just want to add one entry per flight, something like this:
Origin - Airline - Flight Number - Due - Arrived
There is tr tag for each flight and inside each tr tag is the information shown above. I'm not sure how to detect when I reach the end of the tag for a particular flight so I can group the information into one string, rather than adding each td tag individually. There is a blank string at the start or end of each tr tag, but again I can't work out how to concatenate the values per td tag into one string, rather than adding each value on a seperate line.
Any ideas?
I got this working actually using the implementation below.
HtmlNodeCollection table = htmlDocument.DocumentNode.SelectNodes("//tr");
HtmlNodeCollection rows = table[0].SelectNodes("//td");
for (int i = 0; i < rows.Count; ++i)
{
string flight = rows[i].InnerHtml.Trim();
if (!flight.Contains(".jpg"))
{
item += flight + " - ";
}
else
{
lstFlights.Items.Add(item);
item = "";
}
}
You should probably try adding an int that counts up to 5. Then from loops 1- 5 , add the results to a string or var. Then only on the 5th loop dump that variable to the list as a single item. You then want to reset your counter to 0 and begin again.
Int i =1;
String item = String.Empty;
foreach (HtmlNode node in htmlDocument.DocumentNode.SelectNodes("//td"))
{
if(i =<5)
{
item += node.ChildNodes[0].InnerHtml.Trim();
i++;
}
if (i == 5)
{
lstResults.Items.Add(item);
i = 0;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.