Joe Tyman
Joe Tyman

Reputation: 1417

A problem parsing a HTML tag with HTML Agility Pack C#

This seems like it should be a easy thing to do but I am having some major issues with this. I am trying to parse for a specific tag with the HAP. I use Firebug to find the XPath I want and come up with //*[@id="atfResults"]. I believe my issue is with the " since the signals the start and end of a new string. I have tried making it a literal string but I have errors. I have attached the functions

        public List<string> GetHtmlPage(string strURL)
    {
        // the html retrieved from the page

        WebResponse objResponse;
        WebRequest objRequest = System.Net.HttpWebRequest.Create(strURL);
        objResponse = objRequest.GetResponse();
        // the using keyword will automatically dispose the object 
        // once complete
        using (StreamReader sr =
        new StreamReader(objResponse.GetResponseStream()))
        {//*[@id="atfResults"]
            string strContent = sr.ReadToEnd();
            // Close and clean up the StreamReader
            sr.Close();
            /*Regex regex = new Regex("<body>((.|\n)*?)</body>", RegexOptions.IgnoreCase);

            //Here we apply our regular expression to our string using the 
            //Match object. 
            Match oM = regex.Match(strContent);
            Result = oM.Value;*/

            HtmlDocument doc = new HtmlDocument();
            doc.Load(new StringReader(strContent));
            HtmlNode root = doc.DocumentNode;
            List<string> itemTags = new List<string>();



            string listingtag = "//*[@id="atfResults"]";

            foreach (HtmlNode link in root.SelectNodes(listingtag))
            {
                string att = link.OuterHtml;

                itemTags.Add(att);
            }

            return itemTags;
        }

    }

Upvotes: 0

Views: 764

Answers (2)

Simon Mourier
Simon Mourier

Reputation: 138776

Have you tried this:

  string listingtag = "//*[@id='atfResults']";

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

You can escape it:

string listingtag = "//*[@id=\"atfResults\"]";

If you wanted to use a raw string, it would be:

string listingtag = @"//*[@id=""atfResults""]";

As you can see, raw strings don't really provide a benefit here.

However, you can instead use:

HtmlNode link = doc.GetElementById("atfResults");

This will also be slightly faster.

Upvotes: 1

Related Questions