xml XSLT - 循环遍历所有子节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18707047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XSLT - Looping through all child nodes
提问by dscl
Don't shoot I'm just the messenger here, but I have some xml that looks like this
不要开枪,我只是这里的信使,但我有一些看起来像这样的 xml
<XMLSnippet>
<data>
<stuff value="stuff" />
<stuff value="more stuff" />
<stuff value="even more stuff" />
<widget value="you expected stuff didn't you" />
<stuff value="great, we've got stuff again" />
</data>
</XMLSnippet>
And I would like to loop through all the datachild nodes and output the following
我想遍历所有data子节点并输出以下内容
stuff
more stuff
even more stuff
you expected stuff didn't you
great, we've got stuff again
Should it matter I am limited to using XSLT 1.0
如果有关系,我只能使用 XSLT 1.0
Thanks!
谢谢!
回答by dscl
Thanks to Phil and the suggestions of Alexandre here is the code I got working
感谢菲尔和亚历山大的建议,这是我工作的代码
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/XMLSnippet">
<xsl:for-each select="data/*">
<xsl:value-of select="@value" />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
回答by PhillyNJ
This is a basic XSLT question, so I am assuming you have little experience with xsl by your post. You need to understand how xslt processes a XML document which is beyond the scope of this post. Nevertheless, this should get you started. Please note, there are several ways to get the output you want, this is only one of them:
这是一个基本的 XSLT 问题,因此我假设您的帖子几乎没有使用 xsl 的经验。您需要了解 xslt 如何处理超出本文范围的 XML 文档。尽管如此,这应该让你开始。请注意,有多种方法可以获得您想要的输出,这只是其中一种:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="XMLSnippet">
<xsl:for-each select="data/stuff">
<xsl:value-of select="@value"/>
</xsl:for-each>
</xsl:template>
For starters, the template match="/" is your entry point. The apply-templates is an xslt instruction that tells the xslt processor to apply the template of the node in context. In this case your root node "XMLSnippet".
首先,模板 match="/" 是您的入口点。apply-templates 是一条 xslt 指令,它告诉 xslt 处理器在上下文中应用节点的模板。在这种情况下,您的根节点“XMLSnippet”。
The for-each select="data/stuff" should be self explanatory as well as the value-of select="@value", except the @ is used to select an attribute.
for-each select="data/stuff" 和 value-of select="@value" 应该是不言自明的,除了 @ 用于选择属性。
Good Luck. May I suggest you read this book XSLT 2.0. A great book on XSLT.
祝你好运。我建议您阅读这本书XSLT 2.0。一本关于 XSLT 的好书。

