简体   繁体   中英

XPath for following-sibling and self node?

As in the code:

<body>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div><span>6</span></div>
  <div>7</div>
  <div>8</div>
</body>

Find preceding-sibling and self node?

Need to get:

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div><span>6</span></div>

I tried to write like this:

//div[span]/self::node()[self::node() and self::node()/preceding-sibling::div]

...but it doesn't work.

This XPath,

//div[span or following-sibling::div[span]]

will select all div elements with a span child or that are siblings before such a div element:

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div><span>6</span></div>

as requested.

Alternative, but probably less efficient:

//span[parent::div]/following::div[1]/preceding::div

Select the preceding div elements of the first div which follows the span element.

Output:

Element='<div>1</div>'
Element='<div>2</div>'
Element='<div>3</div>'
Element='<div>4</div>'
Element='<div>5</div>'
Element='<div>
   <span>6</span>
</div>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM