XPath Select all children with specific parent node by attribute

html-agility-pack xml xpath

Question

I want to select all children i.e images whose parent div with id is testRoot. The structure is unknown. I have simplified it here for understanding purpose. If it is XPath expression, that will be great.

        <div id="testRoot">

<div class="panel">
                    <a tabindex="-1" href="/mafuae/en/p/1236018">
                        <picture>
                            <source srcset="/medias/sys_master/images/images/h4e/hf5/8820729217054/NikonSlr-H-Tablet.jpg" media="(min-width: 768px)">
                            <img src="" alt="NikonSlr_H_Desktop.jpg">
                        </source>
                        </source></source></picture>
                    </a>
                </div>
            <div class="panel">
                    <a tabindex="-1" href="/mafuae/en/storespromotions">
                        <picture>
                            <source srcset="/medias/sys_master/images/images/h73/hd7/8818984321054/Ramadan2-14thMay-Tablet.jpg" media="(min-width: 768px)">
                            <img src="" alt="Ramadan2_14thMay_Desktop.jpg">
                        </source></source></source></picture>
                    </a>
                </div>
</div>

This is what i tried but...

doc.DocumentNode.SelectNodes("//div[@id='hero']/div/div")

Accepted Answer

For the div element with an id attribute of hero //div[@id='hero'], these XPath expression will select elements as follows:

  • //div[@id='hero']/* will select all of its children elements.
  • //div[@id='hero']/img will select all of its children img elements.
  • //div[@id='hero']//* will select all of its descendent elements.
  • //div[@id='hero']//img will select all of its descendent img elements.


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