繁体   English   中英

XSLT for-each循环和具有不同模式的节点

[英]XSLT for-each loop and nodes with different pattern

我具有以下要转换的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>

如您所见,不同章节中的字幕没有永久性模式。 在输出中,我需要将字幕设置在与xml中相同的位置。 对于段落标签,我使用了for-each循环。 像这样:

<xsl:template match="chapter">
  <xsl:for-each select="paragraph">
    <xsl:value-of select="."/>
  </xsl:for-each>
</xsl:template>

现在,我需要按照xml中的顺序在段落之间或段落之间设置字幕。 我怎样才能做到这一点? 请帮忙!

通过使用

 <xsl:for-each select="paragraph">

您首先要提取所有段落元素,可以将其更改为

<xsl:for-each select="*">

要按顺序处理所有元素,但最好避免使用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>&#10;&#10;</xsl:text>
 <xsl:value-of select="."/>
<xsl:text>&#10;&#10;</xsl:text>
</xsl:template>

这样可以吗?

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM