如何获得在XSLT下面的兄弟(How to get the following sibling in

2019-07-29 02:27发布

我是相当新的XSLT,这是我的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>

如果我有一个项目,并希望得到它后面的兄弟,我怎么能做到这一点?

此代码似乎并没有为我工作:

/projects[title="Project X"]/following-sibling

Answer 1:

这实际上是一个完全的XPath问题。

使用方法

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

这将选择任何先上后下的兄弟Project的任何Project在XML文档中的顶部元素,并在其之一的至少字符串值的子元素title孩子是字符串"Project X"

XSLT -基于验证:

<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>

当这种转化应用所提供的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>

XPath表达式求值和正确地选择的元素被复制到输出:

<project>
   <number>2</number>
   <title>Project Y</title>
</project>


文章来源: How to get the following sibling in XSLT
标签: xml xslt xpath