2011-09-30 36 views
0

我有下面的輸入XML文件:極端XSLT XML壓扁

<root> 
<a> 
    <b>1</b> 
</a> 
<c> 
    <d> 
    <e>2</e> 
    <f>3</f> or <e>3</e> 
    </d> 
    <g h="4"/> 
    <i> 
    <j> 
     <k> 
     <l m="5" n="6" o="7" /> 
     <l m="8" n="9" o="0" /> 
     </k> 
    </j> 
    </i> 
</c> 
</root> 

我想用XSLT把它改造成後續輸出:

輸出1

<root> 
    <row b="1" e="2" f="3" h="4" m="5" n="6" o="7" /> 
    <row b="1" e="2" f="3" h="4" m="8" n="9" o="0" /> 
<root> 

OUTPUT 2

<root> 
    <row b="1" e="2" h="4" m="5" n="6" o="7" /> 
    <row b="1" e="2" h="4" m="8" n="9" o="0" /> 
    <row b="1" e="3" h="4" m="5" n="6" o="7" /> 
    <row b="1" e="3" h="4" m="8" n="9" o="0" /> 
<root> 

任何人都可以幫助我的XSLT不是很強大。謝謝。

+0

你需要2個XSLT文件,換句話說,執行2個轉換? –

+0

是的,我猜他們會非常相似。 – David

+0

那麼,你能解釋一下邏輯嗎? –

回答

0

如果你讓的<e>發生確定外環構建您的<row> S和擁有對所有<l>個內循環迭代會更容易。

嘗試這樣:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:template match="/"> 
     <xsl:apply-templates /> 
    </xsl:template> 

    <xsl:template match="root"> 
     <root> 
      <xsl:apply-templates /> 
     </root> 
    </xsl:template> 

    <xsl:template match="e"> 
     <!-- store values of 'e' and 'f' in params --> 
     <xsl:param name="value_of_e" select="." /> 
     <xsl:param name="value_of_f" select="ancestor::d[1]/f" /> 
     <!-- iterate over all 'l's --> 
     <xsl:for-each select="//l"> 
      <xsl:element name="row"> 
       <xsl:attribute name="b"> 
        <xsl:value-of select="//b" /> 
       </xsl:attribute> 
       <xsl:attribute name="e"> 
        <xsl:value-of select="$value_of_e" /> 
       </xsl:attribute> 
       <!-- only include 'f' if it has a value --> 
       <xsl:if test="$value_of_f != ''"> 
        <xsl:attribute name="f"> 
         <xsl:value-of select="$value_of_f" /> 
        </xsl:attribute> 
       </xsl:if> 
       <xsl:attribute name="h"> 
        <xsl:value-of select="ancestor::c[1]/g/@h" /> 
       </xsl:attribute> 
       <xsl:attribute name="m"> 
        <xsl:value-of select="./@m" /> 
       </xsl:attribute> 
       <xsl:attribute name="n"> 
        <xsl:value-of select="./@n" /> 
       </xsl:attribute> 
       <xsl:attribute name="o"> 
        <xsl:value-of select="./@o" /> 
       </xsl:attribute> 
      </xsl:element> 
     </xsl:for-each> 
    </xsl:template> 

    <xsl:template match="b" /> 
    <xsl:template match="f" /> 
    <xsl:template match="g" /> 
</xsl:stylesheet>