[英]Is there a better way to do the following XSLT
I am learning XSLT and doing some simple examples to get a better taste of it. 我正在学习XSLT,并通过一些简单的例子来更好地了解它。 I want to transform a XML file to html via XSLT.
我想通过XSLT将XML文件转换为html。 Here is my XML:
这是我的XML:
<structure>
<part class="H1" id="h11"/>
<part class="H2" id="h21"/>
<part class="H3" id="h31"/>
<part class="H4" id="h41"/>
<part class="H5" id="h51"/>
<part class="H6" id="h61"/>
</structure>
<style>
<property part-name="h11" name="text">This is a h1 heading</property>
<property part-name="h21" name="text">This is a h2 heading</property>
<property part-name="h31" name="text">This is a h3 heading</property>
<property part-name="h41" name="text">This is a h4 heading</property>
<property part-name="h51" name="text">This is a h5 heading</property>
<property part-name="h61" name="text">This is a h6 heading</property>
</style>
And here is my simple XLST: 这是我简单的XLST:
<xsl:key name="headings" match="property[@name='text']" use="@part-name"/>
<xsl:template match="part[@class='H1']">
<h1>
<xsl:value-of select="key('headings', @id)"/>
</h1>
</xsl:template>
<xsl:key name="headings" match="property[@name='text']" use="@part-name"/>
<xsl:template match="part[@class='H2']">
<h2>
<xsl:value-of select="key('headings', @id)"/>
</h2>
</xsl:template>
<xsl:template match="part[@class='H3']">
<h3>
<xsl:value-of select="key('headings', @id)"/>
</h3>
</xsl:template>
<xsl:template match="part[@class='H4']">
<h4>
<xsl:value-of select="key('headings', @id)"/>
</h4>
</xsl:template>
<xsl:template match="part[@class='H5']">
<h5>
<xsl:value-of select="key('headings', @id)"/>
</h5>
</xsl:template>
<xsl:template match="part[@class='H6']">
<h6>
<xsl:value-of select="key('headings', @id)"/>
</h6>
</xsl:template>
As you can see, it is very verbose and repetitive. 如您所见,它非常冗长和重复。 Is there a way via some XPath expression to make it shorter and actually do the job in a better way?
是否可以通过某些XPath表达式使它更短并且实际上以更好的方式完成工作? Perhaps, something like a regEx?
也许像regEx这样的东西? Another way I can think of is with the use of
<xsl:if>
and have the whole thing inside one single template, but that's not much of an improvement IMO. 我可以想到的另一种方法是使用
<xsl:if>
并将整个内容放在一个模板中,但这并不是IMO的很大改进。
I think you want 我想你要
<xsl:template match="part[starts-with(@class, 'H')]">
<xsl:element name="h{translate(@class, 'H', '')}">
<xsl:value-of select="key('headings', @id)"/>
</xsl:element>
</xsl:template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.