html - XSLT- 元素的动态嵌套
我正在处理从XML输入输出HTML的样式表。我必须根据输入中元素列表的位置在输出文件中生成不同的嵌套级别。例如,NEWS [1]和NEWS [2]应该嵌套在相同的元素下以及NEWS [3]和NEWS [4]。
这是XML输入的一个例子:
<NEWS_LIST>
<NEWS>
<TITLE>Title of the notice #1</TILE>
<IMG_URL>http://media/image_1.png</IMG_URL>
</NEWS>
<NEWS>
<TITLE>Title of the notice #2</TILE>
<IMG_URL>http://media/image_2.png</IMG_URL>
</NEWS>
<NEWS>
<TITLE>Title of the notice #3</TILE>
<IMG_URL>http://media/image_3.png</IMG_URL>
</NEWS>
<NEWS>
<TITLE>Title of the notice #4</TILE>
<IMG_URL>http://media/image_4.png</IMG_URL>
</NEWS>
</NEWS_LIST>
所需的HTML输出:
<div class="middle>
<div class="unit 1">
<div class="unit 2">
<img src="http://media/image_1.png"/>
<p>Title of the notice #1</p>
</div>
<div class="unit 2">
<img src="http://media/image_2.png"/>
<p>Title of the notice #2</p>
</div>
</div>
<div class="unit 1">
<div class="unit 2">
<img src="http://media/image_3.png"/>
<p>Title of the notice #3</p>
</div>
</div class="unit 2">
<img src="http://media/image_4.png"/>
<p>Title of the notice #4</p>
</div>
</div>
</div>
我正在使用XSLT position()函数来选择元素和输出文件,但我不知道如何嵌套孩子。任何帮助都会非常感激。
最佳答案:
1 个答案:
答案 0 :(得分:1)
我建议您分两个阶段浏览NEWS
个节点:
-
- 第一阶段:匹配所有奇数位置节点:
<xsl:apply-templates select="NEWS[(position() mod 2)=1]" mode="unit1"/>
醇>
...并且对于每一个,将第二阶段应用于它和下一阶段:
<xsl:template match="NEWS" mode="unit1"> <div class="unit 1"> <xsl:apply-templates select="." mode="unit2"></xsl:apply-templates> <xsl:apply-templates select="following-sibling::NEWS[1]" mode="unit2"/> </ div> </xsl:template>
- 第一阶段:匹配所有奇数位置节点:
-
- 第二阶段:打印处理的每个节点。
<xsl:template match="NEWS" mode="unit2"> <div class="unit 2"> <img src="{IMG_URL}" /> <p><xsl:value-of select="TITLE"/></p> </ div> </xsl:template>
- 第二阶段:打印处理的每个节点。
请注意,有两个匹配NEWS
的模板,但它们在mode
中有所不同(适用于每个阶段)。
本文经用户投稿或网站收集转载,如有侵权请联系本站。