如果 XML 标签未排序,则以正确的顺序应用模板

apply-templates in the right order if the XML tags are not ordered

我正在尝试转换 XLST 转换,我得到以下 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>

<?xml-stylesheet type="text/xsl" href="xlstransfo.xsl"?>

<breakfast_menu>

<food>
<name>Belgian Waffles</name>
<price>.95</price>
<description>
two of our famous Belgian Waffles with plenty of real maple syrup
</description>
<calories>650</calories>
</food>

<food>
<name>Strawberry Belgian Waffles</name>
<description>
light Belgian waffles covered with strawberries and whipped cream
</description>
<price>.95</price>
<calories>900</calories>
</food>

<food>
<name>Berry-Berry Belgian Waffles</name>
<price>.95</price>
<description>
light Belgian waffles covered with an assortment of fresh berries and whipped cream
</description>
</food>

</breakfast_menu>

我这个XML的问题是子节点不一定是同一个顺序

我尝试做一个 XLS 以在 HTML 中转换它:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
    <body>
         <xsl:apply-templates select="/breakfast_menu/food"/>
    </body>
</html>

</xsl:template>

<xsl:template match="/breakfast/food">
<xsl:apply-templates select="name"/>
<xsl:apply-templates select="price"/>
<xsl:apply-templates select="description"/>
<xsl:apply-templates select="calories"/>
</xsl:template>

<xsl:template match="/breakfast_menu/food/name">
    <div style="background-color:3366FF; font-weight:bold; color:FFFFFF;display:inline">
        <xsl:value-of select="."/>
    </div>
</xsl:template>

<xsl:template match="/breakfast_menu/food/price">
    <div style="color:white;background-color:3366FF;display:inline">
        <xsl:value-of select="."/></div>
        <br />
</xsl:template>

<xsl:template match="/breakfast_menu/food/description">
    <div style="background-color:C0C0C0;display:inline">
        <xsl:value-of select="."/>
    </div>
</xsl:template>

<xsl:template match="/breakfast_menu/food/calories">
    <div style="background-color:C0C0C0;font-style:italic;display:inline">
        <xsl:value-of select="."/> calories per serving</div>
    <br />
</xsl:template>

</xsl:stylesheet>

元素总是按照 XML 中标签的顺序出现。这意味着我得到了第一个项目的正确名称 - 价格 - 描述 - 卡路里订单,然后是第二个项目的错误名称 - 描述 - 价格 - 卡路里。

我如何从 XLST 中解决这个问题(不修改 XML 文件)?

我正在使用 Altova XMLSpy 进行转换。

问题出在这一行...

<xsl:template match="/breakfast/food"> 

breakfast 不是您的 XML 中的元素,因此此模板不会匹配任何内容。相反,built-in templates 将适用,这将 select food 的子项按文档顺序排列。

你应该改成这样...

<xsl:template match="/breakfast_menu/food">

事实上,在这种情况下不需要完整路径。您也可以将其替换为:

<xsl:template match="food">

其他模板也是如此。例如 <xsl:template match="/breakfast_menu/food/price"> 可以替换为 <xsl:template match="price">。例如,如果您在层次结构的不同部分具有相同名称的元素,并且需要应用不同的模板,那么您只需要完整路径。