Xpath 2.0 query - how to check if the current element is the first element with this name in an XML document

I have the following xsl template:

<xsl:template match="para"> <fo:block xsl:use-attribute-sets="paragraph.para"> <!-- if first para in document --> <!--<xsl:if test="//para[1] intersect .">--> <xsl:if test="//para[1] intersect ."> <xsl:attribute name="space-after">10pt</xsl:attribute> <xsl:attribute name="background-color">yellow</xsl:attribute> </xsl:if> <xsl:choose> <xsl:when test="preceding-sibling::*[1][self::title]"> <xsl:attribute name="text-indent">0em</xsl:attribute> </xsl:when> <xsl:when test="parent::item"> <xsl:attribute name="text-indent">0em</xsl:attribute> </xsl:when> <xsl:otherwise> <xsl:attribute name="text-indent">1em</xsl:attribute> </xsl:otherwise> </xsl:choose> <xsl:apply-templates/> </fo:block> </xsl:template> 

The problem I ran into is checking that the current template node is the very first para node in the document from the following xml:

 <document> <section> <paragraph> <para>Para Text 1*#</para> <para>Para Text 2</para> </paragraph> </section> <paragraph> <para>Para Text 3*</para> <para>Para Text 4</para> <para>Para Text 5</para> <sub-paragraph> <para>Para Text 6*</para> <para>Para Text 7</para> </sub-paragraph> </paragraph> <appendix> <paragraph> <para>Para Text 8*</para> </paragraph> <paragraph> <para>Para Text 9</para> </paragraph> </appendix> </document> 

The xpath I'm currently using is "// para [1] intersect." which selects the first pair for each pair group (indicated by * in the XML sample). Any ideas on how I can simply select the first occurrence of steam in the document (indicated by #)?

+4
source share
2 answers

In XPath 1.0 (XSLT 1.0) you can use :

 count( (//para)[1] | .) = 1 

This also works in XPath 2.0, but may not be as efficient as using the intersect operator.

I would recommend the following XPath 2.0 expression :

 (//para)[1] is . 

Note the use of the XPath 2.0 is statement .

+6
source

I myself developed a solution, you need a small change in the brackets of adding xpath around the // para parameter restricts the choice:

"(// para) [1] intersect." you can also use "(// para) [1]". to get the same result, and in this case I believe that the version of "is" is more readable.

+1
source

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


All Articles