WP7的HTML敏捷性 - Silverlight c#

时间:2011-09-01 08:45:07

标签: c# xml linq windows-phone-7 html-agility-pack

我目前正在尝试从HTML文档中解析DIV中的特定表格。

我有这个工作窗口Silverlight,但WP7 HTML敏捷包似乎是一个完全不同的东西。

HTML看起来像这样

<div id="FlightInfo_FlightInfoUpdatePanel">

   <table cellspacing="0" cellpadding="0"><tbody>
     <tr class="">
     <td class="airline"><img src="/images/airline logos/NZ.gif" title="AIR NEW ZEALAND LIMITED. " alt="AIR NEW ZEALAND LIMITED. " /></td>
     <td class="flight">NZ8</td>
     <td class="codeshare">&nbsp;</td>
     <td class="origin">San Francisco</td>
     <td class="date">01 Sep</td>
     <td class="time">17:15</td>
     <td class="est">18:00</td>
     <td class="status">DEPARTED</td>
     </tr>

我目前正在使用此代码解析“FlightInfo_FlightInfoUpdatePanel”DIV Box中的表格

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using HtmlAgilityPack;

namespace Auckland_Airport
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            var doc = new HtmlDocument();
            doc.LoadHtml("http://www.SourceURL");

            var flightTableCell = doc.DocumentNode.Descendants("div")
                 .FirstOrDefault(x => x.ID = "FlightInfo_FlightInfoUpdatePanel")
                 .Element("table")
                 .Element("tbody")
                 .Elements("td")
                 .FirstOrDefault(x => x.Attributes.Contains("flight"));

            var value = flightTableCell.InnerText; 

这会产生未处理的异常错误:

MainPage.PhoneApplicationPage_Loaded(Object sender, RoutedEventArgs e)
   at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
   at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

var flightTableCell =
    doc.DocumentNode
        .Descendants("div")
        .FirstOrDefault(x => x.Id == "FlightInfo_FlightInfoUpdatePanel")
        .Element("table")
        .Element("tbody")
        .Elements("td")
        .FirstOrDefault(x => x.Attributes.Contains("flight"));

var value = flightTableCell.InnerText;  
this.textBlock1.Text = value;

由于您无法使用xpath,因此您不得不手动遍历DOM。