以预定义顺序进行XSLT节点转换

时间:2011-04-16 08:35:03

标签: xslt

如何按照xml节点顺序进行转换?

xml文件是这样的

<root>  
    <paragraph>First paragraph</paragraph>
    <paragraph>Second paragraph</paragraph>
    <unordered_list>
       <list_name>Unordered list name</list_name>
       <list_element>First element</list_element>
       <list_element>Second element</list_element>    
    </unordered_list>
    <paragraph>Third paragraph</paragraph>
</root>

我想将其转换为HTML

...
<p>First paragraph</p>
<p>Second Paragraph</p>
<h3>Unordered list name</h3>
<ul>
    <li>First element</li>
    <li>Second element</li>
</ul>
<p>Third paragraph</p>
...

当我使用 xsl:for-each 时 它首先输出所有段落然后输出列表,或者反过来输出。 我想保持XML文件的顺序。 我知道这可能是非常基本的,但我似乎无处使用 xsl:choose xsl:if 。所以,请帮助我。

2 个答案:

答案 0 :(得分:1)

以下是一个示例xslt样式表,它完全符合您的要求:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <!-- iterate through all the child nodes, 
    and apply the proper template to them -->
    <xsl:template match="/">
        <!-- added an extra div tag, to create a correct xml
        that contains only one root tag -->
        <div>
            <xsl:apply-templates />
        </div>
    </xsl:template>

    <!-- create the **p** tags -->
    <xsl:template match="paragraph">
        <p>
            <xsl:value-of select="text()" />
        </p>
    </xsl:template>

    <!-- create the **ul** tags -->
    <xsl:template match="unordered_list">
        <h3>
            <xsl:value-of select="list_name" />
        </h3>
        <ul>
            <xsl:apply-templates select="list_element" />
        </ul>
    </xsl:template>

    <!-- create the **li** tags -->
    <xsl:template match="list_element">
        <li>
            <xsl:value-of select="text()" />
        </li>
    </xsl:template>
</xsl:stylesheet>

此转换的输出将为:

<?xml version="1.0" encoding="UTF-8"?>
<div>
    <p>First paragraph</p>
    <p>Second paragraph</p>
    <h3>Unordered list name</h3>
    <ul>
        <li>First element</li>
        <li>Second element</li>
    </ul>
    <p>Third paragraph</p>
</div>

答案 1 :(得分:1)

更短且更合理的转型

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="paragraph">
     <p><xsl:apply-templates/></p>
 </xsl:template>

 <xsl:template match="unordered_list/list_name">
  <h3><xsl:apply-templates/></h3>
 </xsl:template>

 <xsl:template match="unordered_list/list_element"/>

 <xsl:template match="unordered_list/list_element[1]">
  <ul>
   <xsl:apply-templates mode="list"
        select=".|following-sibling::*"/>
  </ul>
 </xsl:template>

 <xsl:template mode="list" match="unordered_list/list_element">
  <li><xsl:apply-templates/></li>
 </xsl:template>
</xsl:stylesheet>
相关问题