按照評論:
如果什麼元素都不在隨之而來的訂單?
在這種情況下(假設XSLT 1.0),可以使用translate()
來獲取元素的ID,然後搜索通過正確的名稱使用concat()
相應的要素爲基礎。我會將following-sibling::
軸更改爲../
(parent::
的縮寫),以確保最終捕獲當前的firstname
之前的元素。
<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="customers">
<MyCustomers>
<xsl:apply-templates select="*[starts-with(name(),'firstname')]"/>
</MyCustomers>
</xsl:template>
<xsl:template match="*[starts-with(name(),'firstname')]">
<xsl:variable name="id" select="translate(name(),'firstname','')"/>
<Customer>
<Name><xsl:value-of select="concat(.,' ',
../*[name()=concat('lastname',$id)])"/></Name>
<Sex><xsl:value-of select="../*[name()=concat('sex',$id)]"/></Sex>
</Customer>
</xsl:template>
</xsl:stylesheet>
作廢答案
假設如圖問題固定輸入文檔結構,一個優良的工作XSLT 1.0變換是:
<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="customers">
<MyCustomers>
<xsl:apply-templates select="*[starts-with(name(),'firstname')]"/>
</MyCustomers>
</xsl:template>
<xsl:template match="*[starts-with(name(),'firstname')]">
<Customer>
<Name><xsl:value-of select="concat(.,' ',
following-sibling::*[1]
[starts-with(name(),'lastname')])"/></Name>
<Sex><xsl:value-of select="following-sibling::*[2]
[starts-with(name(),'sex')]"/></Sex>
</Customer>
</xsl:template>
</xsl:stylesheet>
小解釋
由於XML輸入中標記的悲傷名稱,您需要XPath 1.0函數starts-with()
。您可以使用following-sibling::
軸獲取名稱以firstname
開頭的任何元素的所需以下兄弟標籤。
請使用'code'標記並過帳您的帖子。 –
好問題,+1。使用XSLT 1.0查看我的答案,獲得最通用,最靈活的解決方案。即使頂層元素的子元素以任意方式重新洗牌,它也會產生想要的結果。 :) –
還補充說明。 –