NameSpace Manager or XsltContent to parse aspx page

asp.net c# html-agility-pack linq

Question

How can I use NameSpace Manager or XsltContent to parse aspx page?

I am using HtmlAgilityPack.

I am trying to parse aspx page to get Button and Label controls IDs. I am getting the following error when I try to select node with asp:Button element.

Here is the error message:

Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.

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

My aspx page looks as follows:

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

Accepted Answer

I use Linq with the Agility Pack myself, rather than XPath, how about this?

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



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why