Skip to content Skip to sidebar Skip to footer

How To Bind Html Parse (hap) To Listbox Datatemplate

I am currently running the below code to parse an HTML link using HTML Agility Pack for WP7. EDIT ******************************** Code with suggested changes void client_Downloa

Solution 1:

publicclassFlight
{    
    publicstring Airline { get; set; }
    publicstring Flight { get; set; }
    public DateTime Time { get; set; }    
}

This is your code:

var node = doc.DocumentNode.Descendants("div")
        .FirstOrDefault(x => x.Id == "FlightInfo_FlightInfoUpdatePanel")
        .Element("table")
        .Element("tbody")
        .Elements("tr").Aggregate("Flight list\n", (acc, n) => acc + "\n" + n.OuterHtml);

After

List<Flight> flightList=newList<Flight>();
foreach (HtmlNode tr in node){
    flightList.Add(newFlight(){    
        Airline=tr.Descendants("td")
            .FirstOrDefault(f=>f.Attributes["class"].Value=="airline").InnerHtml,
        Flight=tr.Descendants("td")
            .FirstOrDefault(f=>f.Attributes["class"].Value=="flight").InnerText// Insert other properties here
    });    
}

listbox1.ItemsSource=flightList;

Solution 2:

You could create a simple model object that you bind to your UI:

publicclassFlight
{    
    publicstring Airline { get; set; }
    publicstring Flight { get; set; }
    public DateTime Time { get; set; }    
}

Then use a Select projection to convert your document into a list of flights:

var node = doc.DocumentNode.Descendants("div")
    .FirstOrDefault(x => x.Id == "FlightInfo_FlightInfoUpdatePanel")
    .Element("table")
    .Element("tbody")
    .Elements("tr").Aggregate("Flight list\n", (acc, n) => acc + "\n" + n.OuterHtml);

List<Flight> flights = node.Elements("td").Select(i =>newFlight()
           {
              Airline = i.Element("td").Single(j => j.Attribute("class") == "airline").Value,
              Flight = i.Element("td").Single(j => j.Attribute("class") == "flight").Value,
              ...
           }

Then bind this list of Flight instances to your UI.

I am not familiar with HTML Agility Pack, so I am assuming that its Linq API is similar, or the same as Linq to XML. You might have to tweak the query code above a little bit, but the general approach should be fine.

Post a Comment for "How To Bind Html Parse (hap) To Listbox Datatemplate"