0
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")
Robert
  • 10,403
  • 14
  • 67
  • 117
user1492051
  • 886
  • 8
  • 22

1 Answers1

1

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");
}
Kyle W
  • 3,702
  • 20
  • 32
  • because xpath2 gets children of xpath1 and i want to keep track of the chidren, check the html example – user1492051 Mar 28 '14 at 19:18
  • I updated my answer to account for the children being off of the head. They're distinct elements, and you want to know that they're distinct elements. There's no reason to combine the xpaths and put them in one query. – Kyle W Mar 28 '14 at 19:19
  • Everything I'm looking at says it can. See this for an example: http://stackoverflow.com/questions/857198/htmlagilitypack-selecting-childnodes-not-as-expected – Kyle W Mar 28 '14 at 19:24
  • SelectNodes returns a NodeCollection you can't call SelectNodes Again – user1492051 Mar 28 '14 at 19:27
  • What do you mean "I am trying to avoid hard coding things" - the only things that are hard-coded in my EXAMPLE can easily be moved out into a function call or variables or something. Why won't calling SelectNodes on a single collection work? You asked a question, I gave an answer, and you're saying it won't work but won't say why it won't work. That makes it hard to help. The example uses XPath only, so I'm not sure what that's about. – Kyle W Mar 28 '14 at 19:37