【问题标题】:struck with for-each in xslt 2.0?在 xslt 2.0 中使用 for-each 吗?
【发布时间】:2012-08-28 06:39:52
【问题描述】:

这是我的 xml 文档。我想使用 xslt2.0 将其转换为另一种 xml 格式。

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
                    xmlns:v="urn:schemas-microsoft-com:vml">
        <w:body>

            <w:tbl/>
            <w:tbl/>
       </w:body>
      </w:document>

这是我的 xslt 2.0 代码片段。

<xsl:for-each select="following::node()[1]">
    <xsl:choose>
        <xsl:when test="self::w:tbl and (parent::w:body)">
                <xsl:apply-templates select="self::w:tbl"/>
        </xsl:when>
    </xsl:choose>
</xsl:for-each> 


<xsl:template match="w:tbl">
    <table>
      table data
    </table>
</xsl:template>

我生成的输出是:

<table>
     table data
   <table>
       table data
    </table>
 </table>

但我需要的输出是:

<table>
     table data
</table>
<table>
     table data
</table>

【问题讨论】:

  • 你真的必须使用这些“for-each”功能吗?这在选择“following::node”等时非常难看......

标签: xml xslt xpath xslt-2.0 xpath-2.0


【解决方案1】:

您没有说执行 xsl:for-each 时上下文项是什么。您没有向我们提供这些信息这一事实可能表明您还没有理解上下文在 XSLT 中的重要性。在不知道上下文是什么的情况下,不可能更正您的代码。

如果您的代码是正确的,那么整个 for-each 可以简化为

<xsl:apply-templates select="following::node()[1][self::w:tbl][parent::w:body]"/>

【讨论】:

    【解决方案2】:

    如果您希望转换 w:tbl 元素,这些元素是 w:body 元素的子元素,您可以让模板匹配随后看起来的 body 元素对于 tbl 元素

    <xsl:template match="w:body">
       <xsl:apply-templates select="w:tbl"/>
    </xsl:template>
    

    匹配 w:tbl 的模板将和以前一样。这是完整的 XSLT:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
       xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" 
       exclude-result-prefixes="w">
       <xsl:output method="xml" indent="yes"/>
    
       <xsl:template match="/*">
          <xsl:apply-templates select="w:body"/>
       </xsl:template>
    
       <xsl:template match="w:body">
          <xsl:apply-templates select="w:tbl"/>
       </xsl:template>
    
       <xsl:template match="w:tbl">
          <table> table data </table>
       </xsl:template>
    </xsl:stylesheet>
    

    当应用于您的示例 XML 时,将输出以下内容

    <table> table data </table>
    <table> table data </table>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多