输入XML使用XSL输出XML

输入XML使用XSL输出XML,xml,xslt,Xml,Xslt,我有一个问题,我无法理解将一个xml转换为另一个xml的XSL代码 这是输入xml: 这是输出xml: 最后我忘了元素车的结尾 谢谢。使用XSLT实际上很容易做到这一点;最难的部分是钥匙的使用。以下是您需要的代码: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:k

我有一个问题,我无法理解将一个xml转换为另一个xml的XSL代码

这是输入xml:

这是输出xml:

最后我忘了元素车的结尾


谢谢。

使用XSLT实际上很容易做到这一点;最难的部分是钥匙的使用。以下是您需要的代码:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:key name="distances" match="distance" use="id_car" />

  <xsl:template match="output">
    <xsl:apply-templates select="cars" />
  </xsl:template>

  <xsl:template match="car">
    <xsl:copy>
      <xsl:apply-templates />
      <distances>
        <xsl:apply-templates select="key('distances', id)" />
      </distances>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="distance">
    <distance day="{date}">
      <xsl:value-of select="distance" />
    </distance>
  </xsl:template>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
关键点本质上允许您使用关键点功能获取id为给定值的所有距离元素的列表

第一个模板处理根并仅输出cars元素

第二个模板处理任何car元素,按原样输出它们,但添加一个distance元素,并使用key函数处理具有正确ID的任何distance元素


最后一个模板是“身份”模板,它复制了我们尚未准确说明的任何元素;这将处理品牌、类型、许可证元素等。

我看不出有任何问题???构成这种分组的XSL代码是什么样子的?我是否必须使用与cars-element和distance-element中的id匹配的变量?我应该使用什么结构来执行此操作?你能给我举个例子吗。。。您将如何用xsl编写此代码?
<?xml version="1.0" encoding="ISO-8859-1" ?>
<cars>
  <car>
    <id>1</id> 
    <brand>Audi</brand>
    <type>A3</type>
    <license>B-01-TST</license>
    <distances>
      <distance day="20110901">111</distance>
      <distance day="20110902">23</distance>
      <distance day="20110903">0</distance>
    </distances>
  </car>
  <car>
    <id>2</id>
    <brand>Volkwagen</brand>
    <type>Golf</type>
    <license>IF-02-TST</license>
    <distances>
      <distance day="20110901">92</distance>
      <distance day="20110902">87</distance>
      <distance day="20110903">132</distance>
    </distances>
  </car>
</cars>
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:key name="distances" match="distance" use="id_car" />

  <xsl:template match="output">
    <xsl:apply-templates select="cars" />
  </xsl:template>

  <xsl:template match="car">
    <xsl:copy>
      <xsl:apply-templates />
      <distances>
        <xsl:apply-templates select="key('distances', id)" />
      </distances>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="distance">
    <distance day="{date}">
      <xsl:value-of select="distance" />
    </distance>
  </xsl:template>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>