[英]How to use different xpath in a for-each loop for a XSLT transform
這就是問題:轉換后的XSLT應該顯示兩個電話號碼,<Phone_1>和<Phone_2>,每個電話號碼一個。 僅添加傳真標簽以供參考。
這是我要轉換的XML的片段:
<DirPartyContactInfoView>
<Locator>08-922100</Locator>
<Type>Phone</Type>
</DirPartyContactInfoView>
<Locator>073-6564865</Locator>
<Type>Phone</Type>
</DirPartyContactInfoView>
<Locator>08-922150</Locator>
<Type>Fax</Type>
</DirPartyContactInfoView>
這是我目前對此片段的XSLT的看法。 到目前為止,我已經嘗試將變量設置為條件,知道它只能設置變量值一次而不能修改它。
<xsl:for-each select="DirPartyContactInfoView">
<xsl:choose>
<xsl:when test="Type='Phone'">
<xsl:variable name="Phone1" />
<xsl:choose>
<xsl:when test="Phone1=''">
<xsl:variable name="Phone1" select="Locator" />
<Phone_1>
<xsl:value-of select="Locator" />
</Phone_1>
</xsl:when>
<xsl:otherwise>
<Phone_2>
<xsl:value-of select="Locator" />
</Phone_2>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<xsl:when test="Type='Fax'">
<Fax>
<xsl:value-of select="Locator" />
</Fax>
</xsl:when>
</xsl:choose>
</xsl:for-each>
然而,我在輸出上得到了兩個<Phone_2>,而我完全沒有想法。 我猜我不能使用這樣的變量。 有任何解決這個問題的方法嗎?
對於(看似)簡單的要求,這非常復雜。 如果我理解你的話,試試這個:
<xsl:template match="/">
<xsl:apply-templates select='root/DirPartyContactInfoView[Type="Phone"]' />
</xsl:template>
<xsl:template match='DirPartyContactInfoView'>
<xsl:element name='phone_{position()}'>
<xsl:value-of select='Locator' />
</xsl:element>
</xsl:template>
我假設一個根節點root
因為你的XML沒有向我們展示你擁有的根節點。
演示 (參見輸出源 )。
XSLT中一個好的經驗法則是,如果你發現自己嚴重依賴for-each
構造或變量,那么可能有更好的方法。
你真的需要一個xsl:for-each
循環嗎? 您也可以直接使用XPath訪問<Locator>
元素:
//DirPartyContactInfoView[1]/Locator
//DirPartyContactInfoView[2]/Locator
如果你仍然需要xsl:for-each
循環,也許這樣的東西會有所幫助:
<xsl:for-each select="DirPartyContactInfoView">
<xsl:choose>
<xsl:when test="Type='Phone'">
<xsl:choose>
<xsl:when test="position()='1'">
<Phone_1>
<xsl:value-of select="Locator" />
</Phone_1>
</xsl:when>
<xsl:otherwise>
<Phone_2>
<xsl:value-of select="Locator" />
</Phone_2>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
</xsl:choose>
</xsl:for-each>
@flaskis已經通過更改問題回復了之前的答案,所以我有點不願意權衡,但可能是這里有一個合適的解決方案
<xsl:template match="phone[1]">...</xsl:template>
<xsl:template match="phone[2]">...</xsl:template>
其中不同的模板規則應用於第一和第二電話元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.