简体   繁体   English

使用属性作为键(xsl)合并相似的数据xml节点

[英]Merge similar data xml nodes using an attribute as key ( xsl )

I want to convert a file with N sections with this format: 我想用以下格式转换N个部分的文件:

<File>
        <Sections Section="Section1" fieldName="field1" fieldValue="value1"/>
        <Sections Section="Section1" fieldName="field2" fieldValue="value2"/>
        <Sections Section="Section1" fieldName="field3" fieldValue="value3"/>
        <Sections Section="Section2" fieldName="field1" fieldValue="value1"/>
        <Sections Section="Section2" fieldName="field2" fieldValue="value2"/>
        <Sections Section="Section2" fieldName="field3" fieldValue="value3"/>
</File>

Into 进入

<File>
   <Section1 field1="value1" field2="value2" field3="value3"/>
   <Section2 field1="value1" field2="value2" field3="value3"/>
</File>

Using attribute Section's value as key to create elements. 使用属性Section的值作为创建元素的键。

I tried somethings, but i couldn't. 我尝试了一些东西,但是没有。

Could you help me? 你可以帮帮我吗?

Thanks. 谢谢。

Here is an XSLT 1.0 stylesheet: 这是XSLT 1.0样式表:

<xsl:stylesheet 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output indent="yes"/>

  <xsl:key name="k1" match="File/Sections" use="@Section"/>

  <xsl:template match="File">
    <xsl:copy>
      <xsl:apply-templates select="Sections[generate-id() = generate-id(key('k1', @Section)[1])]" mode="group"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Sections" mode="group">
    <xsl:element name="{@Section}">
      <xsl:apply-templates select="key('k1', @Section)"/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="Sections">
    <xsl:attribute name="{@fieldName}">
      <xsl:value-of select="@fieldValue"/>
    </xsl:attribute>
  </xsl:template>

</xsl:stylesheet>

And here's the XSLT 2.0 stylesheet 这是XSLT 2.0样式表

<xsl:stylesheet version="2.0" 
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/File" >
        <xsl:copy>
        <xsl:for-each-group select="Sections" group-by="@Section">
            <xsl:element name="{current-grouping-key()}">
                <xsl:for-each select="current-group()">
                    <xsl:attribute name="{@fieldName}" select="@fieldValue"/>
                </xsl:for-each>
            </xsl:element>
        </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM