[英]XSLT for-each loop and nodes with different pattern
I have the following structure of xml data to transform: 我具有以下要转换的xml数据结构:
<chapter>
<title>Text</title>
<subtitle>Text</subtitle>
<paragraph>Text</paragraph>
<paragraph>Text</paragraph>
<subtitle>Text</subtitle>
<paragraph>Text</paragraph>
<other>Text</other>
</chapter>
<chapter>
<title>Text</title>
<paragraph>Text</paragraph>
<paragraph>Text</paragraph>
<paragraph>Text</paragraph>
<other>Text</other>
</chapter>
<chapter>
<title>Text</title>
<paragraph>Text</paragraph>
<subtitle>Text</subtitle>
<paragraph>Text</paragraph>
<paragraph>Text</paragraph>
<other>Text</other>
</chapter>
As you can see, the subtitles in the different chapters have no permanent pattern. 如您所见,不同章节中的字幕没有永久性模式。 In the output, I need to set the subtitles on the same place like the are in the xml.
在输出中,我需要将字幕设置在与xml中相同的位置。 For the paragraph tags, I use a for-each loop.
对于段落标签,我使用了for-each循环。 Like this:
像这样:
<xsl:template match="chapter">
<xsl:for-each select="paragraph">
<xsl:value-of select="."/>
</xsl:for-each>
</xsl:template>
And now, I need to set the subtitles above, between or among the paragraphs in the order they are in the xml. 现在,我需要按照xml中的顺序在段落之间或段落之间设置字幕。 How can I do this?
我怎样才能做到这一点? Please help!
请帮忙!
By using 通过使用
<xsl:for-each select="paragraph">
You are pulling all the paragraph elements out first, You could change that to 您首先要提取所有段落元素,可以将其更改为
<xsl:for-each select="*">
To process all elements in order, but it is better (or at least more idiomatic xslt) to avoid for-each and use apply-templates instead. 要按顺序处理所有元素,但最好避免使用for-each(或至少使用更多惯用的xslt),而应使用apply-templates。
<xsl:template match="chapter">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="title">
Title: <xsl:value-of select="."/>
</xsl:template>
<xsl:template match="subtitle">
SubTitle: <xsl:value-of select="."/>
</xsl:template>
<xsl:template match="paragraph">
<xsl:text> </xsl:text>
<xsl:value-of select="."/>
<xsl:text> </xsl:text>
</xsl:template>
Would this do it? 这样可以吗?
<xsl:template match="chapter">
<xsl:for-each select="paragraph | subtitle">
<xsl:value-of select="."/>
</xsl:for-each>
</xsl:template>
But as David Carlisle points out, the typical XSLT approach is to split this out into templates, and this especially makes sense if you want special handling for certain ones: 但是正如David Carlisle指出的那样,典型的XSLT方法是将其拆分为模板,如果您希望对某些模板进行特殊处理,则这尤其有意义:
<xsl:template match="chapter">
<xsl:apply-templates select="paragraph | subtitle" />
</xsl:template>
<xsl:template match="paragraph">
<xsl:value-of select="." />
</xsl:template>
<xsl:template match="subtitle">
<!-- do stuff with subtitles -->
</xsl:template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.