如何使LINQ to XML和HTML协同工作?

时间:2008-12-09 17:43:56

标签: html xml linq-to-xml parsing

我有一个html表

  <table border="0" width="100%">
        <tr class="headerbg">
            <th width="5%">
                No
            </th>
            <th width="30%">
                Name
            </th>
            <th width="20%">
                Department or Division
            </th>
            <th width="25%">
                Email
            </th>
            <th width="20%">
                Staff/Student
            </th>
        </tr>
        <tr class="bg2">
            <td>
                1
            </td>
            <td>
                <strong><a class="searchLink2" href="tel_search.php?fore=Dave&amp;sur=Rumber">Dave Rumber</a></strong>
            </td>
            <td>
                Medical School
            </td>
            <td>
                <a class="searchLink2" href="mailto:Dave.Rumber@Home.com">Dave.Rumber@Home.com</a>
            </td>
            <td>
                Student&nbsp;
            </td>
        </tr>
    </table>

有时会有多行人的结果。 我希望能够遍历每一行并提取名称和电子邮件信息并进行其他处理。将数据放在数据网格中,并可能放入数据库中。

我想我的问题是我该怎么做?

  string table = GetContents(buffer);

  table = table.Replace("&nbsp;", "");
  table = table.Replace("&", "&amp;");

  XElement inters = XElement.Parse(table);

我可以把它放入XElement但是我不太确定从哪里开始!

谢谢!

2 个答案:

答案 0 :(得分:1)

您实际上可以使用HTML表作为OLE DB的数据源:

http://connectionstrings.com/html-table

完全披露:我实际上并没有尝试过这个 - 但我猜它会比尝试用HTML解析XML容易得多。

答案 1 :(得分:1)

这是一些应该让你入门的手绘代码。不要在生产中这样做,这只是一个教育示范。

List<XElement> rows = inters
  .Descendants
  .Where(x => x.Name == "tr")
  .Skip(1) //header
  .ToList();
//
// and now to turn rows into people
List<Person> people = rows
  //filter to anchor.  should be two.
  .Select(r => r.Descendants.Where(a => a.Name = "a"))
  //Project each anchor pair into a Person
  .Select(g => new Person()
  {
    Name = g.First().Value,
    Email = g.Skip(1).First().Value
  })
  .ToList();
相关问题