Grouping the nodes by matching attribute

My input xml looks as shown below, I need to group the tag based on the id attribute. Even if the id attribute of tag is same in the next row, then it should be grouped under the previous tag.

<Layouts>
<Layout id="1">
<Structure id="2000">
<Row id="1">
<Col id="125"/>
</Row>
<Row id="2">
<Col id="126"/>
</Row>
<Row id="3">
<Col id="125"/>
</Row>
</Structure>
</Layout>

<Layout id="2">
<Structure id="3000">
<Row id="1">
<Col id="125"/>
</Row>
<Row id="2">
<Col id="226"/>
</Row>
<Row id="3">
<Col id="226"/>
</Row>
<Row id="4">
<Col id="125"/>
</Row>
</Structure>
</Layout>
</Layouts>

My output xml should look like this,

<Layouts>
<Layout id="1">
<Structure id="2000">
<Row id="1">
<Col id="125"/>
<Col id="125"/>
</Row>
<Row id="2">
<Col id="126"/>
</Row>          
</Structure>
</Layout>

<Layout id="2">
<Structure id="3000">
<Row id="1">
<Col id="125"/>
<Col id="125"/>
</Row>
<Row id="2">
<Col id="226"/>
<Col id="226"/>
</Row>          
</Structure>
</Layout>
</Layouts>

As we can see, each row should be grouped with similar id attribute values and finally it should be displayed in a single . This grouping should only happen for each section. For each node, the similar id's should be grouped inside node. I tried the xsl:for-each-group, but the id's are not getting grouped exactly inside . Can anyone pls help..

Answers


Assuming all you need to group is the Col elements and you can use XSLT 2.0 here is a stylesheet:

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

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

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* , node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="Structure">
  <xsl:copy>
    <xsl:apply-templates select="@*"/>
    <xsl:for-each-group select="Row" group-by="Col/@id">
      <xsl:copy>
        <xsl:apply-templates select="@* , current-group()/node()"/>
      </xsl:copy>
    </xsl:for-each-group>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Need Your Help

Create a new format option for Maven Assembly plugin

maven maven-plugin iso maven-assembly-plugin iso9660

The Maven Assembly plugin allows different formats to be specified in the assembly descriptor. How can I develop a new format so it will be supported?

Why doesn't .find() work with urllib.request.urlopen() in python 3?

python python-3.x

Trying to transition from urllib in python 2 to python 3. I can output the html source using .urlopen() but I can't index it using .find() method.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.