我有一个像这样的xml元素:
<book>
<English color="blue" author="hasan" />
<English color="red" author="david" />
</book>
是否可以使用xslt迭代它并生成如下所示的输出?
<book>
<English color="yellow" author="hally" />
<English color="pink" author="gufoo" />
</book>
这是我正在尝试的那个;
<xsl:template match = /book>
<xsl:for-each select "./English">
<xsl:if test="@color = '"yellow"'">
<English color="yellow"/>
<xsl:if test="@color = '"red"'">
<English color="pink"/>
</xsl:for-each>
</xsl-template>
答案 0 :(得分:0)
尝试以下样式表。我摆脱了xsl:for-each元素因为我觉得用这种方式做起来更简单。此外,在像XSL这样的声明性语言中使用foreach循环对我来说似乎并不合适。我更愿意将它们留给命令式语言。
有许多不同的方法可以达到这样的结果。您应该花点时间尝试修改它并进行一些实验。 作为练习,您可以删除if语句并尝试使用模板和谓词来实现类似的结果。在你这样做之前,你可能不得不阅读一些关于XSL的教程。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Copy every element or attribute encountered
and find matching templates for its attributes
and child elements
-->
<xsl:template match="@*|*">
<xsl:copy>
<xsl:apply-templates select="@*|*"></xsl:apply-templates>
</xsl:copy>
</xsl:template>
<!-- For every attribute named "color" that has a value of red or blue,
follow the conditions defined in if blocks.
Notice that the specified color attributes will not be copied according
to the template above as the one selected is always the last
matching one in your XSL.
This way both the "author" attributes and "color" attributes with values
different than red and blue will be matched by the other template.
The dot "." means the currently processed node (usually element or attribute)
-->
<xsl:template match="@color[. = 'blue' or . = 'red']">
<xsl:attribute name="color">
<xsl:if test=". = 'blue'">yellow</xsl:if>
<xsl:if test=". = 'red'">pink</xsl:if>
</xsl:attribute>
</xsl:template>