2012-07-11 66 views
2

我已经看了看所以下面和类似的链接来解析aspx页面和谷歌使用HTMLAgilityPack写LINQ使用HtmlAgilityPack

Parse html document using HtmlAgilityPack

解析aspx页面,但我不知道怎么写LINQ声明这样我可以在我的aspx页面中识别按钮和标签控件名称。

这是我的aspx页面。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="WebApplication1.WebForm4" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 

      <asp:Button ID="Button1" runat="server" Text="Button on page4" /> 
     <br /> 
     <br /> 
     <asp:Label ID="Label1" runat="server" Text="Label on page 4"></asp:Label> 
     <br /> 
        <br /> 
     <asp:Button ID="Button2" runat="server" Text="second button page 4" /> 

         <br /> 
     <asp:Button ID="Button3" runat="server" Text="second button page 4" /> 



    </div> 
    </form> 
</body> 
</html> 

我想使用HTML敏捷包,这样我可以列出以下输出写LINQ:此页面上

控件是Button1的,Label1的,Button2的,将Button3

我有编写LINQ解析aspx页面时出现问题。请帮忙。

这是我写到目前为止,它不工作。

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument(); 

    htmlDoc.OptionFixNestedTags = true; 

    string filePath = @"C:\WebApplication1\webform4.aspx"; 


    htmlDoc.Load(filePath); 

     htmlDoc.Load(filePath); 


     var pagecontrols = from links in htmlDoc.DocumentNode.Descendants("div") 
          where links.Attributes.Contains("runat") 
          select links.Attributes["ID"].Value; 

     foreach (var pagecontrol in pagecontrols) 
     { 
      Response.Write(pagecontrol); 
     } 
+0

在findItemPrices中设置了什么?你是什​​么意思,它不工作? – 2012-07-11 22:41:31

+0

我无法访问每个控件。已将findItemPrices更新为pageControls – 2012-07-11 22:43:07

+0

您的变量应具有不是ASP.NET控件的HTML元素的集合。你想要访问什么? – 2012-07-11 22:44:54

回答

2

如果我正确理解你的问题,你需要做的是这样的:

var pagecontrols = from links in htmlDoc.DocumentNode.Descendants("div") 
        where links.Attributes.Contains("runat") 
        select links.Attributes["ID"].Value; 
+0

我刚刚试过你的代码,我在pageControls中没有得到任何东西 – 2012-07-11 22:59:59

+0

@ dotnet-practitioner:那么你接受了这个答案,但根本无法使用'HtmlAgilityPack'解析一个aspx页面? – 2013-07-08 10:57:10

0

我不知道你是否已经找到了这个答案,但这里是解决方案的工作。

HtmlAgilityPack.HtmlDocument doc = new HtmlDocument(); 
HtmlNode.ElementsFlags.Remove("form"); 
doc.LoadHtml(aspPage); 
var elements = doc.DocumentNode.Descendants("div"); 
var pageControls = from z in elements.ChildNodes 
        where z.Attributes.Contains("runat") //server controls 
        select z.Attributes["ID"].Value;