如何使用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>

最佳答案

我将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 );
}

09-15 19:56