【问题标题】:how to change nesting structure in XML using XSLT?如何使用 XSLT 更改 XML 中的嵌套结构?
【发布时间】:2022-12-07 22:52:21
【问题描述】:

我是一个完整的 XSLT 新手,但我需要将它用于我正在从事的项目。

我有一个看起来像这样的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>

<table>
   <CLASS>
      <Name></Name>
      <Sex></Sex>
      <Age></Age>
      <Height></Height>
      <Weight></Weight>
   </CLASS>
</table>

我想要的输出应该是这样的

<table>
   <CLASS>
      <Name> 
     <Sex>
          <Age>
              <Height>              
            <Weight>
            </Weight>
          </Height>
         </Age>
        </Sex>
      </Name>
   </CLASS>
</table>

我现在已经花了 2 天,但我无法为此找到解决方案。我尝试使用 for-each 并阅读了有关分组的信息,但不确定如何在嵌套结构中执行此类更改。我正在使用 XSLT 1。

【问题讨论】:

  • 请解释转换所需的逻辑:什么决定哪个元素进入哪个?只是它们出现的顺序吗?

标签: xml nested xslt-1.0


【解决方案1】:

这看起来并不适合“一个完整的 XSLT 新手”。

假设 CLASS 下的每个元素都应该嵌套在其紧邻的前一个兄弟元素中,您可以采用一种称为“兄弟递归”的方法:

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="/table">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="CLASS">
    <xsl:copy>
        <xsl:apply-templates select="*[1]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="CLASS/*">
    <xsl:copy>
        <xsl:apply-templates select="following-sibling::*[1]"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    相关资源
    最近更新 更多