2012-12-26 83 views
1

我想将一张表从维基百科放入xml文件,然后解析为C#。可能吗?如果是,我可以保存在xml中吗标题类型列吗?如何从维基百科获取表格

HtmlWeb web = new HtmlWeb(); 
HtmlDocument doc = web.Load("http://en.wikipedia.org/wiki/2012_in_film"); 

HtmlNode node = doc.DocumentNode.SelectSingleNode("//table[@class='wikitable']"); 

回答

1

您可以使用网络浏览器:

//First navigate to your address 
webBrowser1.Navigate("http://en.wikipedia.org/wiki/2012_in_film"); 
     List<string> Genre = new List<string>(); 
     List<string> Title = new List<string>(); 
    //When page loaded 
    foreach (HtmlElement table in webBrowser1.Document.GetElementsByTagName("table")) 
      { 
       if (table.GetAttribute("className").Equals("wikitable")) 
       { 
        foreach (HtmlElement tr in table.GetElementsByTagName("tr")) 
        { 
         int columncount = 1; 
         foreach (HtmlElement td in tr.GetElementsByTagName("td")) 
         { 
          //Title 
          if (columncount == 4) 
          { 
           Title.Add(td.InnerText); 
          } 
          //Genre 
          if (columncount == 7) 
          { 
           Genre.Add(td.InnerText); 
          } 
          columncount++; 
         } 

        } 
       } 
      } 

现在你有两个列表(体裁和标题)。 你可以简单地将它们转换为XML文件

1

您可以使用此代码: 搜索要查找并正则表达式来分析数据的其余部分的html标记。 此代码将搜索宽度为150的表格并获取所有网址/导航网址。

HtmlElementCollection links = webBrowser1.Document.GetElementsByTagName("table"); //get collection in link 
       { 
        foreach (HtmlElement link_data in links) //parse for each collection 
        { 
         String width = link_data.GetAttribute("width"); 
         { 
          if (width != null && width == "150") 
          { 
           Regex linkX = new Regex("<a[^>]*?href=\"(?<href>[\\s\\S]*?)\"[^>]*?>(?<Title>[\\s\\S]*?)</a>", RegexOptions.IgnoreCase); 
           MatchCollection category_urls = linkX.Matches(link_data.OuterHtml); 
           if (category_urls.Count > 0) 
           { 
            foreach (Match match in category_urls) 
            { 
              //rest of the code 
            } 
           } 
          } 
         } 
        } 
       }