XSLT通过元素中提供的密钥对节点进行分组

时间:2019-11-07 17:20:12

标签: xslt

我得到了一个讨厌的XML,其中的节点未按我想要的分组,而我试图找到一种通过节点中提供的<master_key>将其分组的方法:

原始xml

<root>
   <zasoba>
      <kod>388300-56</kod>
      <description>50cm</description>
      <master_key>388300MK</master_key>
      <kategorie/>
   </zasoba>
   <zasoba>
      <kod>388300-53</kod>
      <description>53cm</description>
      <master_key>388300MK</master_key>
      <kategorie/>
   </zasoba>
   <zasoba>
      <kod>388300MK</kod>
      <description>Master</description>
      <kategorie/>
   </zasoba>
   <zasoba>
      <kod>388399-56</kod>
      <description>56cm</description>
      <master_key>388399MK</master_key>
      <kategorie/>
   </zasoba>
   <zasoba>
      <kod>388399-57</kod>
      <description>57cm</description>
      <master_key>388399MK</master_key>
      <kategorie/>
   </zasoba>
   <zasoba>
      <kod>388399MK</kod>
      <description>Master 2</description>
      <kategorie/>
   </zasoba>
</root>

产品变体在各个元素中分开,但是我想在主元素(由master_key定义)下移动到新元素名称<variant>下。

输出应如下所示:

<root>
   <zasoba>
      <kod>388300MK</kod>
      <description>Master 2</description>
      <kategorie/>
      <variant>
         <kod>388300-56</kod>
         <description>50cm</description>
         <master_key>388300MK</master_key>
         <kategorie/>
      </variant>
      <variant>
         <kod>388300-53</kod>
         <description>53cm</description>
         <master_key>388300MK</master_key>
         <kategorie/>
      </variant>
   </zasoba>
   <zasoba>
      <kod>388399MK</kod>
      <description>Master</description>
      <kategorie/>
      <variant>
         <kod>388399-56</kod>
         <description>56cm</description>
         <master_key>388399MK</master_key>
         <kategorie/>
      </variant>
      <variant>
         <kod>388399-57</kod>
         <description>57cm</description>
         <master_key>388399MK</master_key>
         <kategorie/>
      </variant>
   </zasoba>
</root>

1 个答案:

答案 0 :(得分:1)

幸运的是,XPath足够灵活,可以按所需顺序选择分组填充,并选择具有现有值的分组键:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="root">
      <xsl:copy>
          <xsl:for-each-group select="zasoba[not(master_key)], zasoba[master_key]" group-by="(master_key, kod)[1]">
              <xsl:copy>
                  <xsl:apply-templates/>
                  <xsl:apply-templates select="tail(current-group())"/>
              </xsl:copy>
          </xsl:for-each-group>
      </xsl:copy>
  </xsl:template>

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

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/ejivdHb