Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the following sibling in XSLT

Tags:

xml

xslt

xpath

I am fairly new to XSLT and this is my XML:

<projects>
    <project>
        <number>1</number>
        <title>Project X</title>
    </project>
    <project>
        <number>2</number>
        <title>Project Y</title>
    </project>
    <project>
        <number>3</number>
        <title>Project Z</title>
    </project>
</projects>

If I have one project and want to get the sibling that follows it, how can I do that?

This code doesn't seem to work for me:

/projects[title="Project X"]/following-sibling
like image 973
Tintin81 Avatar asked Apr 20 '12 12:04

Tintin81


1 Answers

This is actually a completely XPath question.

Use:

/*/project[title = 'Project X']/following-sibling::project[1]

This selects any first following sibling Project of any Project element that is a child of the top element in the XML document and the string value of at least of one of its title children is the string "Project X".

XSLT - based verification:

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

 <xsl:template match="/">
     <xsl:copy-of select=
      "/*/project[title = 'Project X']/following-sibling::project[1]"/>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:

<projects>
    <project>
        <number>1</number>
        <title>Project X</title>
    </project>
    <project>
        <number>2</number>
        <title>Project Y</title>
    </project>
    <project>
        <number>3</number>
        <title>Project Z</title>
    </project>
</projects>

the XPath expression is evaluated and the correctly-selected element is copied to the output:

<project>
   <number>2</number>
   <title>Project Y</title>
</project>
like image 144
Dimitre Novatchev Avatar answered Oct 10 '22 01:10

Dimitre Novatchev