Search code examples
c#asp.netxmlxmldocument

load aspx file into xmldocument


I want to be able to load aspx page into XmlDocument variable. How do I do that? Here is what I have tried and its expecting .xml file and not .aspx page. Is there any way to convert aspx page on the fly into xml document and load it? thanks

string filePath = @"C:\WebApplication1\webform4.aspx";
XmlDocument document = new XmlDocument();
document.Load(filePath);

I get the following error:

Name cannot begin with the '%' character, hexadecimal value 0x25. Line 1, position 2.


Solution

  • The reason you're getting that error:

    Name cannot begin with the '%' character, hexadecimal value 0x25. Line 1, position 2.

    is because .aspx pages are often not valid XML. ASP.NET .aspx pages contain directives such as:

    <%@ Page Language="C#" [possibly other stuff] %>
    

    <%@ and %> is not valid XML which is why you can't load the raw ASPX page.

    Now, even if you were to strip out these directives, there's a fairly good chance that unless you've been really, really strict and all of the markup on the page is XHTML, then that won't load either.

    You might want to try and load the page (with or without directives) using the HTML Agility Pack which can be downloaded via NuGet.