当前位置: 首页 > 知识库问答 >
问题:

将元素标识的节点放入一个节点

祁彬
2023-03-14
<ROW>
    <DEPT> A </DEPT>
</ROW>
<ROW>
    <DEPT> B </DEPT>
</ROW>
<ROW>
    <DEPT> A </DEPT>
</ROW>
<DEPTARTMENT>
    <ROW>
        <DEPT> A </DEPT>
    </ROW>
    <ROW>
        <DEPT> A </DEPT>
    </ROW>
</DEPARTMENT>
<DEPTARTMENT>
    <ROW>
        <DEPT> B </DEPT>
    </ROW>
</DEPARTMENT>

共有1个答案

申屠昆
2023-03-14

下面是一个可能的XSLT1.0解决方案。

当此XSLT:

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

  <xsl:key name="kRowByDept" match="ROW" use="DEPT"/>

  <xsl:template match="/*">
    <T>
      <xsl:apply-templates
        select="ROW[generate-id() = generate-id(key('kRowByDept', DEPT)[1])]"/>
    </T>
  </xsl:template>

  <xsl:template match="ROW">
    <DEPARTMENT>
      <xsl:copy-of select="key('kRowByDept', DEPT)"/>
    </DEPARTMENT>
  </xsl:template>
</xsl:stylesheet>

...对提供的XML应用(包装在顶级元素中以使文档格式良好):

<T>
  <ROW>
    <DEPT> A </DEPT>
  </ROW>
  <ROW>
    <DEPT> B </DEPT>
  </ROW>
  <ROW>
    <DEPT> A </DEPT>
  </ROW>
</T>
<T>
  <DEPARTMENT>
    <ROW>
      <DEPT> A </DEPT>
    </ROW>
    <ROW>
      <DEPT> A </DEPT>
    </ROW>
  </DEPARTMENT>
  <DEPARTMENT>
    <ROW>
      <DEPT> B </DEPT>
    </ROW>
  </DEPARTMENT>
</T>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/*">
    <T>
      <xsl:for-each-group select="ROW" group-by="DEPT">
        <DEPARTMENT>
          <xsl:copy-of select="current-group()" />
        </DEPARTMENT>
      </xsl:for-each-group>
    </T>
  </xsl:template>

</xsl:stylesheet>
 类似资料: