Xpath select all child nodes

html html-agility-pack xpath

Question

I need select all child nodes (option tag) from this html:

<select name="akt-miest" id="onoffaci">
<option value="a_0">VÅ¡etci</option>
<option value="a_1">Iba prihlásení</option>
<option value="a_5" selected="selected">Teraz na Pokeci</option>

<optgroup label="Hlavné miestnosti">

<option value="m_13">&nbsp;&nbsp;&nbsp;Bez záväzkov</option>
<option value="m_9">&nbsp;&nbsp;&nbsp;Do pohody</option>
<option value="m_39">&nbsp;&nbsp;&nbsp;Dámsky klub</option>

</optgroup>

I use Html agility pack.

I try this:

 var selectNode = htmlDoc.GetElementbyId("onoffaci");

 var nodes = selectNode.SelectNodes("option::*");

but I get error that xpath has invalid token. What is bad?

For example:

<option value="**a_0**">**VÅ¡etci**</option>

I need get value (a_0) and text VÅ¡etci.

So I try first access to select by Id:

Accepted Answer

I try this:

var selectNode = htmlDoc.GetElementbyId("onoffaci");   
var nodes = selectNode.SelectNodes("option::*"); 

but I get error that xpath has invalid token. What is bad?

The obvious problem is the use of

option::*

option::* means: All nodes in the "option" axis. However there is no "option axis in XPath"

You want:

option

This selects all option elements that are children of the current node.

You can write this in a single XPath expression and omit the getElementbyId() call:

//select[@id='onoffaci']/option

For example:

    <option value="**a_0**">**VÅ¡etci**</option>

I need get value (a_0) and text VÅ¡etci

Use:

    //select[@id='onoffaci']/option/@value 
|
    //select[@id='onoffaci']/option/text()

This selects all value attributes of all option elements that are children of all select elements in the XML document that have an id attribute with value 'onoffaci' and also all text nodes of all option elements that are children of all select elements in the XML document that have an id attribute with value 'onoffaci'.

You will need to iterate the results to get the @value and text() for each option element.

Or:

    //select[@id='onoffaci']/option[1]/@value 
|
    //select[@id='onoffaci']/option[1]/text()

Here you use the observation that the option element you are interested in is the first option child of its parent — now this selects only the value attribute and the text nodes of the wanted option element.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why