NameSpace Manager或XsltContent来解析aspx页面

时间:2012-07-12 00:02:53

标签: c# asp.net linq html-agility-pack

如何使用NameSpace Manager或XsltContent来解析aspx页面?

我正在使用HtmlAgilityPack。

我正在尝试解析aspx页面以获取Button和Label控件ID。当我尝试使用 asp:Button 元素选择节点时,我收到以下错误。

以下是错误消息:

需要命名空间管理器或XsltContext。此查询具有前缀,变量或用户定义的函数。

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

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

        htmlDoc.Load(filePath);

        foreach (HtmlNode div in htmlDoc.DocumentNode.SelectNodes("//div"))
        {
            Response.Write(div.Id);
            foreach (HtmlNode asp in div.SelectNodes("asp:Button"))
            {
                Response.Write(asp.Id);
            }
        }

我的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 id="mydiv">

            <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>

1 个答案:

答案 0 :(得分:6)

我自己使用Linq和Agility Pack,而不是XPath,这个怎么样?

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

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

htmlDoc.Load( filePath );

var aspNodes = htmlDoc.DocumentNode.Descendants().Where( n => n.Name.StartsWith( "asp:" ) );

foreach ( var aspNode in aspNodes ) {
    Console.WriteLine( "Element: {0} Id: {1}", aspNode.Name, aspNode.Attributes["Id"].Value );
}