2012-04-20 51 views
14

下面的兄弟我是相當新的XSLT,這是我的XML:如何獲得在XSLT

<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 

回答

28

這其實是一個完全的XPath問題。

使用

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

這將選擇任何第一以下同級任何Project元素是XML文檔中的頂部元件和一個的至少其title的字符串值的子的Project兒童是字符串"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> 
+0

嘿Dimitre,就像一個魅力。非常感謝! – Tintin81 2012-04-20 20:10:03

+0

@丁丁81:不客氣。 – 2012-04-20 20:28:16