【发布时间】:2011-03-11 08:25:52
【问题描述】:
如何使用 XSLT 转换此 XML 文件:
<file>
<row>
<cell></cell>
<cell>(info...)</cell>
<cell></cell>
</row>
<row>
<cell>first name</cell>
<cell>last name</cell>
<cell>age</cell>
</row>
<row>
<cell>Jim</cell>
<cell>Smith</cell>
<cell>34</cell>
</row>
<row>
<cell>Roy</cell>
<cell>Rogers</cell>
<cell>22</cell>
</row>
<row>
<cell>Hank</cell>
<cell>Grandier</cell>
<cell>23</cell>
</row>
<row>
<cell>(info...)</cell>
<cell></cell>
<cell>(info...)</cell>
</row>
<row>
<cell>Sally</cell>
<cell>Cloud</cell>
<cell>26</cell>
</row>
<row>
<cell>John</cell>
<cell>Randall</cell>
<cell>44</cell>
</row>
</file>
到这个 XML 文件:
<file>
<row>
<cell>Jim</cell>
<cell>34</cell>
</row>
<row>
<cell>Roy</cell>
<cell>22</cell>
</row>
<row>
<cell>Sally</cell>
<cell>26</cell>
</row>
<row>
<cell>John</cell>
<cell>44</cell>
</row>
</file>
基本上规则是:
- 仅第一列和第三列(名字和年龄)
- 仅在特定范围内的行,例如在上面的简单示例中,它将是 rows 3-5 和 rows 7-8 所以我假设我需要某种包含此信息的映射表李>
附录
这是我使用 MarcoS 关于参数的提示的解决方案:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" indent="yes" omit-xml-declaration="no" />
<xsl:param name="range-1-begin" select="3"/>
<xsl:param name="range-1-end" select="4"/>
<xsl:param name="range-2-begin" select="6"/>
<xsl:param name="range-2-end" select="7"/>
<xsl:template match="file">
<marco>
<xsl:for-each select="row">
<xsl:if test="(position() >= $range-1-begin and position() <= $range-1-end)
or (position() >= $range-2-begin and position() <= $range-2-end)">
<row>
<xsl:for-each select="cell">
<xsl:if test="position() = 1 or
position() = 3">
<cell>
<xsl:value-of select="."/>
</cell>
</xsl:if>
</xsl:for-each>
</row>
</xsl:if>
</xsl:for-each>
</marco>
</xsl:template>
</xsl:stylesheet>
【问题讨论】:
-
好问题,+1。请参阅我的答案,以获得使用最基本 XSLT 设计模式之一的完整、简短和简单的解决方案——覆盖身份规则。 :)