![](/img/trans.png)
[英]Basic XML/XSLT - Value-of many nodes when they are have the same name AND When they consists TEXT and other NODES
[英]Basic XML/XSLT - value-of when there are multiple elements of the same name
當我得到在同一個父元素中多次使用的元素的值時,我想得到同名的每個元素而不僅僅是第一個元素。
例如 -
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<artist>Bob Dylan2</artist>
<artist>Bob Dylan3</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
</catalog>
現在當我通過每張CD並使用value-of輸出藝術家名字時,我只得到第一個元素(有點可以理解)。 但是如何在for-each循環中獲取同名的所有元素? 我嘗試做一個內部for-each循環,但沒有工作。
我是非常新的XML及其工作方式,所以請放輕松我...... :-(
<xsl:template match="/">
<xsl:for-each select="catalog">
<!-- Print Other Stuff, if required -->
<xsl:for-each select="cd/artist">
<xsl:value-of select="text()"/><br/>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
鮑勃·迪倫
鮑勃迪倫2
鮑勃迪倫3
現在,當我
for-each
通過每個CD和利用value-of
輸出藝術家的名字,我只得到了第一個元素(有點理解)。 但是如何在for-each
循環中獲取同名的所有元素? 我嘗試做一個內部for-each
循環,但沒有工作。
我對任何XSLT新手的建議是 不 使用<xsl:for-each>
-盡可能的 。 我知道只有一個用例,其中<xsl:for-each>
是必要的,這是一個非常罕見的情況(當需要顯式更改當前文檔以便key()
函數將使用索引時為此特定文件而構建)。
這可能是最簡單的解決方案之一(沒有<xsl:for-each>
且沒有嵌套):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="artist">
<xsl:value-of select="concat(., '
')"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
當此轉換應用於提供的XML文檔時 :
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<artist>Bob Dylan2</artist>
<artist>Bob Dylan3</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
</catalog>
產生了想要的正確結果 :
Bob Dylan
Bob Dylan2
Bob Dylan3
<xsl:template match="catalog/cd/artist">
<xsl:value-of select="." />
</xsl:template>
沒有理由內循環不起作用。 您使用什么XSLT語法來執行此操作? 聽起來你的xpaths中有一個錯誤,因為你所描述的應該可以正常工作。
你的XPATH是錯誤的:
在使用foreach的CD元素中:
<xsl:template match="/">
<xsl:for-each select="//cd">
<xsl:for-each select="artist">
<xsl:message terminate="no">
<xsl:value-of select="."/>
</xsl:message>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
打印所有的藝術家..
text()
xpath語法選擇當前指定節點的任何文本子節點。
有些人並不特別喜歡這個網站,但是為了開始,可以指出你正確的方向 - 點擊這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.