johnnyno
johnnyno

Reputation: 608

XPath selecting only first level of nodes no matter of their position in hierarchy

I have xls data like in below code. How to select only first level of nodes with class="aaa" attribute?

I can not use something like this "//*[@class='aaa']", becuase it will select also level 2.

Also can not put path directly like "/root/div/div[@class='aaa'], because location of nodes inside hierarchy may be vary.

Is there any way to select only first level of nodes no matter on their position inside hierarchy?

<root>
<div>
  <!-- level 1 -->
  <div class="aaa">
    <div>
      <!-- level 2 -->
      <div class="aaa">
      </div>
    </div>

    <div>
      <div>
        <!-- level 2 -->
        <div class="aaa">
        </div>
      </div>
    </div>
  </div>
</div>

<div>
  <div>
    <div>
      <div>
        <div>
          <!-- level 1 -->
          <div class="aaa">
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</root>

Upvotes: 5

Views: 3115

Answers (2)

kool79
kool79

Reputation: 413

.//div[@class='aaa' and not(ancestor::div[@class='aaa']) and not(ancestor::div = self::node())]

Upvotes: 0

har07
har07

Reputation: 89315

One possible XPath :

//div[@class='aaa' and not(ancestor::div[@class='aaa'])]

Basically above XPath select <div> having class equals "aaa" and not having ancestor <div> with class equals "aaa", in other words the outer most <div> having class equals "aaa".

Upvotes: 3

Related Questions