2017-08-21 108 views
0

目标是使用XSLT更改具有相同名称的嵌套XML元素标记。我尝试过使用数字和其他方法。我一直无法获得理想的结果。使用XSLT更改具有相同名称的嵌套XML元素标记

的XML:

<?xml version="1.0" encoding="UTF-8"?> 
<x> 
    <y> 
     <z value="john" designation="manager"> 
      <z value="mike" designation="associate"></z> 
      <z value="dave" designation="associate"></z> 
     </z> 
    </y> 
</x> 

的XSLT:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" /> 
    <xsl:strip-space elements="*" /> 

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

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

    <xsl:template match="//x[y/z/@value='john' and y/z/@value='mike' and y/z/@value='dave']"> 
      <xsl:element name="{@designation}"> 
      <xsl:value-of select="@value"/> 
      </xsl:element>  
    </xsl:template> 

期望的结果:

<?xml version="1.0" encoding="UTF-8"?> 
<employees> 
    <employee> 
     <manager>john 
      <associate>mike</associate> 
      <associate>dave</associate> 
     </manager> 
    </employee> 
</employees> 

回答

0

使用相同的解决方案为您的previous question - 只是为了处理递归嵌套z元素添加一个xsl:apply-templates指令:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
<xsl:strip-space elements="*"/> 

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

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

<xsl:template match="z"> 
    <xsl:element name="{@designation}"> 
     <xsl:value-of select="@value"/> 
     <xsl:apply-templates /> 
    </xsl:element> 
</xsl:template> 

</xsl:stylesheet> 
+0

谢谢迈克尔,但我的目标是让经理标签包围的关联标签。 – Kenny

+0

@Kenny是的,层次被保留。不要让缩进(或缺乏)让你感到困惑。 –

+0

我测试过这个,经理名称出于某种原因关闭了经理标签。 – Kenny

相关问题