简体   繁体   中英

struck with for-each in xslt 2.0?

This is my xml document.I want to convert this to another xml format using xslt2.0.

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

This is my xslt 2.0 code snippt.

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

My generated output is :

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

But My required output is :

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

If you are looking to transform w:tbl elements that are child elements of w:body elements, you could just have a template match the body elements that then looks for the tbl elements

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

The template matching w:tbl would be as before. Here is the full 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>

When applied to your sample XML, the following is output

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

You don't say what the context item is at the point where your xsl:for-each gets executed. The fact that you don't give us this information may suggest that you haven't understood how important context is in XSLT. It's not possible to correct your code without knowing what the context is.

If your code were correct then the whole for-each could be simplified to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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