Xml 每个循环和具有不同模式的节点的XSLT
我有以下要转换的xml数据结构:Xml 每个循环和具有不同模式的节点的XSLT,xml,xslt,xpath,Xml,Xslt,Xpath,我有以下要转换的xml数据结构: <chapter> <title>Text</title> <subtitle>Text</subtitle> <paragraph>Text</paragraph> <paragraph>Text</paragraph> <subtitle
<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>
正文
正文
正文
正文
正文
正文
正文
正文
正文
正文
正文
正文
正文
正文
正文
正文
正文
正文
正如你所看到的,不同章节中的字幕没有固定的模式。在输出中,我需要将字幕设置在与xml中相同的位置。对于段落标记,我使用For-each循环。像这样:
<xsl:template match="chapter">
<xsl:for-each select="paragraph">
<xsl:value-of select="."/>
</xsl:for-each>
</xsl:template>
现在,我需要按照xml中段落的顺序设置上面、段落之间或段落之间的副标题。我该怎么做?请帮忙 这样行吗
<xsl:template match="chapter">
<xsl:for-each select="paragraph | subtitle">
<xsl:value-of select="."/>
</xsl:for-each>
</xsl:template>
但正如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>
通过使用
<xsl:for-each select="paragraph">
首先,您要将所有段落元素都拉出,您可以将其更改为
<xsl:for-each select="*">
按顺序处理所有元素,但最好(或至少更惯用xslt)避免使用for each,而是使用apply模板
<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>
标题:
字幕:
您的预期输出是什么样的?你还没有告诉我们。是的,谢谢你,它解决了一部分问题,我找到了另一部分的解决方案。我把你的建议和一个有字幕的Do-stuff结合起来,这样就有可能用它们做不同的事情了。太好了。不过,如果你的字幕需要特殊处理,按照大卫·卡莱尔(David Carlisle)的建议,将逻辑分割成单独的模板会更为理想。我在上面附上了一个样品。