Html Agility Pack SelectSingleNode giving always same result in iteration?

c# html html-agility-pack selectsinglenode

Question

Even if I iterate SelectSingleNode, I keep obtaining the same object, just a node, even though I want the nodes in the collection. Id is evolving I attempt to find information like values, links, etc. in specially specified components by reading out the web response of a specific site.

int offSet = 0;
string address = "http://www.testsite.de/ergebnisliste.html?offset=" + offSet;

HtmlWeb web = new HtmlWeb();
//web.OverrideEncoding = Encoding.UTF8;
HtmlDocument doc = web.Load(address);

HtmlNodeCollection collection = doc.DocumentNode.SelectNodes("//div[@itemtype='http://schema.org/Posting']");

foreach (HtmlNode node in collection) {
    string id = HttpUtility.HtmlDecode(node.Id);
    string cpname = HttpUtility.HtmlDecode(node.SelectSingleNode("//span[@itemprop='name']").InnerText);
    string cptitle = HttpUtility.HtmlDecode(node.SelectSingleNode("//span[@itemprop='title']").InnerText);
    string cpaddress = HttpUtility.HtmlDecode(node.SelectSingleNode("//span[@itemprop='addressLocality']").InnerText);
    string date = HttpUtility.HtmlDecode(node.SelectSingleNode("//div[@itemprop='datePosted']").InnerText);
    string link = "http://www.testsite.de" + HttpUtility.HtmlDecode(node.SelectSingleNode("//div[@class='h3 title']//a[@href]").GetAttributeValue("href", "default"));               
}

Here is an example of 1 iteration:

<div id="66666" itemtype="http://schema.org/Posting">   
<div>
    <a>
        <img />
    </a>
</div>
<div>
    <div class="h3 title">
        <a href="/test.html"  title="Test">
            <span itemprop="title">Test</span>
        </a>
    </div>
    <div>
        <span itemprop="name">TestName</span>       
    </div>
</div>
<div>
    <div>
        <div>
            <div>
                <span itemprop="address">Test</span>
            </div>
            <span>                     
                <a>
                    <span><!-- --></span>
                    <span></span>
                </a>
            </span>         
        </div>
    </div>      
    <div itemprop="date">
        <time datetime="2013-03-01">01.03.13</time>
    </div>
</div>

1
15
3/3/2013 11:58:46 AM

Accepted Answer

By composing

node.SelectSingleNode("//span[@itemprop='name']").InnerText

similar to you writing

doc.DocumentNode.SelectSingleNode("//span[@itemprop='name']").InnerText

You should format it this way if that's what you want to do:node.SelectSingleNode(".//span[@itemprop='name']").InnerText .

This . Make a search on the current node, which is indicated by a dot or period.node in place ofdoc

39
6/16/2016 4:32:34 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow