XPath "after siblings before"

I am trying to select elements (a) with XPath 1.0 (or possibly with Regex) that follow the siblings of a specific element (b) but only precede another element b.

<img><b>First</b><br>&nbsp;&nbsp;
<img>&nbsp;&nbsp;<a href="/first-href">First Href</a> - 19:30<br>
<img><b>Second</b><br>&nbsp;&nbsp;
<img>&nbsp;&nbsp;<a href="/second-href">Second Href</a> - 19:30<br>
<img>&nbsp;&nbsp;<a href="/third-href">Third Href</a> - 19:30<br>

I tried to make the sample as close as possible to the real world. So, in this case, when I am in the element

<b>First</b>

I need to choose

<a href="/first-href">First Href</a> 

and when i'm in

<b>Second</b> 

I need to choose

<a href="/second-href">Second Href</a> 
<a href="/third-href">Third Href</a>

Any idea how to achieve this? Thank!

+3
source share
2 answers

Dynamically create this XPath:

following-sibling::a[preceding-sibling::b[1][.='xxxx']]

where 'xxxx' is replaced by the text of the current <b>.

, . , preceding following, XPath, .

XSLT :

following-sibling::a[
  generate-id(preceding-sibling::b[1]) = generate-id(current())
]
+5

, XPath.

$ns1 $ns2:

  $ns1[count(. | $ns2) = count($ns2)]

$ns1 <a> siblings, <b> node, $ns2 <a> siblings, <b> node.

, :

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:template match="/">
   <xsl:apply-templates select="*/b"/>
  </xsl:template>

  <xsl:template match="b">
    At: <xsl:value-of select="."/>

    <xsl:variable name="vNextB" select="following-sibling::b[1]"/>

    <xsl:variable name="vA-sAfterCurrentB" select="following-sibling::a"/>

    <xsl:variable name="vA-sBeforeNextB" select=
    "$vNextB/preceding-sibling::a
    |
     $vA-sAfterCurrentB[not($vNextB)]
    "/>

    <xsl:copy-of select=
     "$vA-sAfterCurrentB
              [count(.| $vA-sBeforeNextB)
              =
               count($vA-sBeforeNextB)
               ]
    "/>
  </xsl:template>
</xsl:stylesheet>

XML-:

<t>
    <img/>
    <b>First</b>
    <br />&#xA0;&#xA0;
    <img/>&#xA0;&#xA0;
    <a href="/first-href">First Href</a> - 19:30
    <br />
    <img/>
    <b>Second</b>
    <br />
    <img/>&#xA0;&#xA0;
    <a href="/second-href">Second Href</a> - 19:30
    <br />
    <img/>&#xA0;
    <a href="/third-href">Third Href</a> - 19:30
    <br />
</t>

:

   At: First <a href="/first-href">First Href</a>
    At: Second <a href="/second-href">Second Href</a>
<a href="/third-href">Third Href</a>
+1

Source: https://habr.com/ru/post/1733185/


All Articles