我需要通过删除或复制一个块来将这个XMl转换为另一个块,同时形成像所需输出的块一样,我仍然坚持如何进行格式化
<?xml version="1.0" encoding="ISO-8859-1" ?>
<output>
<cars>
<car>
<id>1</id>
<brand>Audi</brand>
<type>A3</type>
<license>B-01-TST</license>
</car>
<car>
<id>2</id>
<brand>Volkwagen</brand>
<type>Golf</type>
<license>IF-02-TST</license>
</car>
</cars>
<distances>
<distance>
<id_car>1</id_car>
<date>20110901</date>
<distance>111</distance>
</distance>
<distance>
<id_car>1</id_car>
<date>20110902</date>
<distance>23</distance>
</distance>
<id_car>2</id_car>
<date>20110901</date>
<distance>92</distance>
</distance>
<distance>
<id_car>2</id_car>
<date>20110902</date>
<distance>87</distance>
</distance>
</distances>
</output>
进入此输出:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<output>
<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>
</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>
</distances>
</car>
</cars>
</output>
到目前为止,我只能删除距离块并将其添加到正确的位置,但是如何通过car / id组织距离并将日期标记作为属性日添加到距离中? 这是我到目前为止所做的:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@* |node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="distances" />
<xsl:template match="license">
<xsl:copy-of select="."/>
<distances></distances>
</xsl:template>
</xsl:stylesheet>
答案 0 :(得分:1)
使用键来跟踪交叉引用,然后编写模板来转换这些引用的元素:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:strip-space elements="*"/>
<xsl:output indent="yes"/>
<xsl:key name="dist" match="distances/distance" use="id_car"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="distances" />
<xsl:template match="license">
<xsl:next-match/>
<distances>
<xsl:apply-templates select="key('dist', ../id)"/>
</distances>
</xsl:template>
<xsl:template match="distance">
<distance day="{date}">
<xsl:value-of select="distance"/>
</distance>
</xsl:template>
</xsl:transform>