【问题标题】:xslt, how to 'flatten' the tag structure for unknown number of child tagsxslt,如何为未知数量的子标签“展平”标签结构
【发布时间】:2010-12-20 19:38:41
【问题描述】:

我的源文件如下所示:

<x>
<names>
         <name>name1</name>
         <name>name2</name>
</names>
<codes>
         <code>code1</code>
         <code>code2</code>
</codes>
<stuff> stuff </stuff>
</x>

我想对其进行转换以获得此输出:

<out>
<y>
    <name>name1</name>
    <code>code1</code>
    <stuff> stuff </stuff>
</y>
<y>
    <name>name2</name>
    <code>code2</code>
    <stuff> stuff </stuff>
</y>
</out>

我不知道源文件中名称和代码标签的数量,但我知道名称的数量等于代码的数量。

请分享一些技巧,如何做到这一点。

【问题讨论】:

  • 好问题,+1。请参阅我的答案以获得完整而简短的解决方案。 :)

标签: xslt flatten


【解决方案1】:

这种转变

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
  <out>
   <xsl:apply-templates select="names/name"/>
  </out>
 </xsl:template>

 <xsl:template match="name">
  <xsl:variable name="vPos" select="position()"/>
  <y>
   <xsl:copy-of select="."/>
   <xsl:copy-of select=
     "../../codes/code[position()=$vPos]"/>
   <xsl:copy-of select="/*/stuff"/>
  </y>
 </xsl:template>
</xsl:stylesheet>

应用于提供的 XML 文档时

<x>
    <names>
        <name>name1</name>
        <name>name2</name>
    </names>
    <codes>
        <code>code1</code>
        <code>code2</code>
    </codes>
    <stuff> stuff </stuff>
</x>

产生想要的正确结果

<out>
   <y>
      <name>name1</name>
      <code>code1</code>
      <stuff> stuff </stuff>
   </y>
   <y>
      <name>name2</name>
      <code>code2</code>
      <stuff> stuff </stuff>
   </y>
</out>

【讨论】:

  • 完美运行,谢谢。我知道如何在未来进行类似的转换。
猜你喜欢
  • 1970-01-01
  • 2018-03-16
  • 1970-01-01
  • 2016-11-12
  • 2016-12-15
  • 2014-11-17
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
相关资源
最近更新 更多