How to get the following sibling in XSLT

2020-05-19 07:05发布

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

标签: xml xslt xpath
1条回答
【Aperson】
2楼-- · 2020-05-19 07:41

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>
查看更多
登录 后发表回答