【问题标题】:How do I make LINQ to XML and HTML work together?如何使 LINQ to XML 和 HTML 一起工作?
【发布时间】:2008-12-09 17:43:56
【问题描述】:

我有一个 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,但我不太确定从这里去哪里!

谢谢!

【问题讨论】:

    标签: html xml linq-to-xml parsing


    【解决方案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();
    

    【讨论】:

      【解决方案2】:

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

      http://connectionstrings.com/html-table

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-01
        • 1970-01-01
        相关资源
        最近更新 更多