-2

我有一个这样的 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>
4

1 回答 1

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>

于 2012-06-08T18:29:25.810 回答