簡體   English   中英

有沒有更好的方法來執行以下XSLT

[英]Is there a better way to do the following XSLT

我正在學習XSLT,並通過一些簡單的例子來更好地了解它。 我想通過XSLT將XML文件轉換為html。 這是我的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>

這是我簡單的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>

如您所見,它非常冗長和重復。 是否可以通過某些XPath表達式使它更短並且實際上以更好的方式完成工作? 也許像regEx這樣的東西? 我可以想到的另一種方法是使用<xsl:if>並將整個內容放在一個模板中,但這並不是IMO的很大改進。

我想你要

<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM