Reading Current Page XHTML

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • yarbrough40
    Contributor
    • Jun 2009
    • 320

    #1

    Reading Current Page XHTML

    Gang, this is driving me nuts - In a given asp.net page which I have loaded, I would like to read through the XHTML code of that page into a string (that I can do whatever I want with) and for the life of me I cannot figure out how to get at that XHTML page code.

    I naturally assumed that I could use some function existant in the httprequest / response spaces, but I'm coming up empty. I have to believe that this cannot be that hard and I'm missing something simple here. You would be my personal hero if you could share some insight with me.
  • Curtis Rutland
    Recognized Expert Specialist
    • Apr 2008
    • 3264

    #2
    Code:
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.google.com");
    HttpWebResponse res = (HttpWebResponse)req.GetResponse();
    StreamReader reader = new StreamReader(res.GetResponseStream());
    string content = reader.ReadToEnd();
    reader.Close();
    Console.WriteLine(content);
    Does this do what you need? This gets all the text in the stream and dumps it into a string.

    Comment

    • yarbrough40
      Contributor
      • Jun 2009
      • 320

      #3
      well- what you have does work. My problem comes in, though when the controls on the target page are not rendered until the user inputs his parameters and clicks a button. So simply sending the url ("http://www.mypage.aspx ") will not fit the bill. I will somehow need to grab the html at runtime on a button click on the page itself when all the controls have rendered to the page.

      I'm thinking maybe using the RenderControl method to yank the raw html from the page.... not sure

      Comment

      • yarbrough40
        Contributor
        • Jun 2009
        • 320

        #4
        ok so I found a solution that fits my needs.... RenderControl() is the key. It is of my opinion that this is a mega-useful thing to know.

        if anyone cares this is how I did it.

        FIRST you use RenderControl to extract the raw html out of a given control you specify. It could be the entire form if you want. In this example I am grabbing two Label controls. THEN you store that html in a stringbuilder.

        Code:
        Button_Click()
        
                Dim c1 As Control = Label1
                Dim c2 As Control = Label2
        
                Dim sb As New StringBuilder
                Dim sr As New StringWriter(sb)
                Dim htr As New System.Web.UI.HtmlTextWriter(sr)
        
        
                c1.RenderControl(htr)
                c2.RenderControl(htr)
        
            End Sub
        Now you have a string value --> (sb.ToString) that you can do whatever you want with.

        ENJOY!

        Comment

        Working...