Pregunta

var cats = doc.DocumentNode.SelectNodes("xpath1 | xpath2");

I use the | operator to compute multiple nodes and html agilitypack puts them in a single NodeCollection containg all the results, how do I know if the Node is a result of xpath1 or xpath2?

example

 var cats = doc.DocumentNode.SelectNodes("//*[contains(@name,'thename')]/../../div/ul/li/a | //*[contains(@name,'thename')]/../../div/ul/li/a/../div/ul/li/a");

I am trying to build a tree like structure from that the first xpath returns a single element the second xpath returns single or multiple elements, the first xpath is a main tree node and the second xpath are the childeren of that node, and i want to build a List<string,List<string>> from that based on the inner text of the results.

To make it more simple consider the following Html:

<ul>
   <li>
      <h1>Node1</h1>
      <ul>
         <li>Node1_1</li>
         <li>Node1_2</li>
         <li>Node1_3</li>
         <li>Node1_4</li>
      </ul>
   </li>
   <li>
      <h1>Node2</h1>
      <ul>
         <li>Node2_1</li>
         <li>Node2_2</li>
      </ul>
   </li>
   <li>
      <h1>Node3</h1>
      <ul>
         <li>Node3_1</li>
         <li>Node3_2</li>
         <li>Node3_3</li>
      </ul>
   </li>
</ul>

var cats = doc.DocumentNode.SelectNodes("//ul/li/h1 | //ul/li/ul/li")
¿Fue útil?

Solución

Why not just do:

var head = doc.DocumentNode.SelectNodes("xpath1");
var children = head.SelectNodes("xpath2");

?

For the code in the example you would do:

var containerNodes = doc.DocumentNode.SelectNodes("//ul/li");
foreach(var n in containerNodes)
{
  var headNode = n.SelectSingleNode("h1");
  var subNodes = n.SelectNodes("ul/li");
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top