Reputation: 2877
I am parsing HTML to an array using the following code.
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var html = e.Result;
var doc = new HtmlDocument();
doc.LoadHtml(html);
var list = doc.DocumentNode.Descendants("div").ToList();
var node = doc.DocumentNode.Descendants("table")
.FirstOrDefault(x => x.Id == "departures")
.Element("tbody") .Elements("tr")
.Select(tr => tr.Elements("td")
.Select(td => td.InnerText).ToArray()).ToArray();
I am then outputing to Texblock with the below code.
//first line
textBlock1.Text = node[0][0];
textBlock2.Text = node[0][1];
textBlock3.Text = node[0][2];
//Second line
textBlock4.Text = node[1][0];
textBlock5.Text = node[1][1];
textBlock6.Text = node[1][2];
//Third line
textBlock7.Text = node[2][0];
textBlock8.Text = node[2][1];
textBlock9.Text = node[2][2];
My issue is this: The HTMl changes through the day, so some times there isn't and [2] and sometimes there is up to [12].
What I would like to know is how can I wite a conditional statment to check if the array exists and only output if it has a value.
I have tried a conditional statement like below, but it still shows a Unhandled exception when there aren't any node[2] or node[1] results
if (node[2][0].length > 0)
{
textBlock1.Text = node[2][0];
}
Any help will be apprecaited. If you need clarification on this please let me know.
Upvotes: 1
Views: 643
Reputation:
To avoid the invalid index, all the dimensions must be ensured, e.g.
if (node.length > 2 && node[2].length > 0) {
// Okay to use node[2][0]
// Since && is short-circuiting it will never make second
// check if first fails.
}
To me, a more fundamental issue seems to be that the text boxes are not variadic but are fixed (box1, box2, etc). Consider using a different control instead, perhaps a list control of sorts. Then n
items can be added uniformly (and just using a loop construct without need for the first index check). Text boxes can also be dynamically created, but this would not be my first choice.
Happy coding.
Upvotes: 1