【问题标题】:iterate through a repeated tag in xml遍历 xml 中的重复标签
【发布时间】:2012-06-08 17:33:45
【问题描述】:

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

【问题讨论】:

  • 除了属性的值,这里应该有区别吗?
  • 你试过什么?此外,这两个文件仅共享结构,数据完全不同。控制转换的规则是什么?请阅读FAQHow to Ask 了解发布指南。
  • 对不起,如果我的表达方法不正确。我需要的是,如果属性“颜色”是蓝色,它应该被替换为黄色,如果颜色是红色,它应该被替换为粉红色。
  • 答案是肯定的。这是可能的。
  • @tom。我对 xslt 不熟悉,正在看一些教程,你能解释一下吗?

标签: xml xslt


【解决方案1】:

试试下面的样式表。我摆脱了 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>

【讨论】:

  • 您应该将前 2 个模板替换为身份转换 (w3.org/TR/xslt#copying)
  • @DevNull 为真。我想以不同的方式来做这件事,但我在中途改变了主意。我承认它最终有点混乱。
猜你喜欢
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多