![](/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.