2013-10-10 61 views
1

我在这个XML作为我的输入:XSLT:如果标记名称是父节点或子节点,如何更改标记名称?

 <unidad num="2."> 
       <tag></tag> 
       <tag2></tag2> 
     <unidad num="2.1"> 
        <tag></tag> 
        <tag2></tag2>   
        <unidad num="2.1.1"> 
        <tag></tag> 
        <tag2></tag2> 
        <unidad num="2.1.1.1"> 
         <tag></tag> 
         <tag2></tag2> 
        </unidad> 
        </unidad> 
       </unidad> 
      </unidad> 

我的输出应该是:

 <sub> 
       <tag></tag> 
       <tag2></tag2> 
     <sub2> 
        <tag></tag> 
        <tag2></tag2>   
        <sub3> 
        <tag></tag> 
        <tag2></tag2> 
        <sub4> 
         <tag></tag> 
         <tag2></tag2> 
        </sub4> 
        </sub3> 
       </sub2> 
      </sub> 

我无法找到正确的方式来做到这一点。我使用模板的,我有这样的:

<xsl:for-each select="unidad"> 
     <xsl:call-template name="unidades1"/> 
    </xsl:for-each> 

     <xsl:template name="unidades1"> 
    <xsl:element name="sub1"> 
     <xsl:text></xsl:text> 
      </xsl:element> 
      <xsl:if test="position() != last()"> 
     <xsl:apply-templates select="child::*"/> 
    </xsl:if> 
     </xsl:template> 

     <xsl:template match="unidad"> 
      <xsl:call-template name="unidades2"/> 
     </xsl:template> 


     <xsl:template name="unidades2"> 
    <xsl:element name="sub2"> 
     <xsl:text></xsl:text> 
      </xsl:element> 
      <xsl:if test="position() != last()"> 
     <xsl:apply-templates select="child::*"/> 
    </xsl:if> 
     </xsl:template> 

有了这个XSLT,团结报的每一个孩子的第二个条件匹配,所以它写成SUB2,我不知道它是怎么考虑的是另一个单身元素的孩子。任何想法如何达到这个?谢谢!

回答

0

此样式表产生所需的输出。它使用修改后的identity transform以及<unidad>元素的专用模板。

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

<!--standard identity template--> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="unidad"> 
<!--count the number of ancestors that are unidad elements--> 
     <xsl:variable name="unidad-ancestor-count" select="count(ancestor::unidad)"/> 

<!--If there are at least one unidad ancestors then 
    set the suffix to be the count()+1--> 
     <xsl:variable name="suffix"> 
      <xsl:if test="$unidad-ancestor-count>0"> 
       <xsl:value-of select="$unidad-ancestor-count+1"/> 
      </xsl:if> 
     </xsl:variable> 

<!--create a new element using a base name of "sub" and the suffix value --> 
     <xsl:element name="sub{$suffix}"> 
<!--not pushing the @num attribute through the identity template, 
    just descendant nodes--> 
      <xsl:apply-templates /> 
     </xsl:element> 
    </xsl:template> 

</xsl:stylesheet> 
相关问题