Group XML elements by key using XSLT
Content |
Objective
To organise a set of XML elements into groups, such that elements with the same key are placed in the same group, and elements with different keys are placed in different groups
Scenario
Suppose you have a Subversion log created using the --xml
and -v
options:
svn log --xml -v
The elements in the log are grouped by revision number. Each revision affects one or more paths, and each path is affected by one or more revisions. Here is a simplified illustration of the structure:
<?xml version="1.0"?> <log> <logentry revision="3"> <date>2010-12-20T13:15:00Z</date> <paths> <path action="M">/trunk/hello.c</path> </paths> </logentry> <logentry revision="2"> <date>2010-12-20T12:00:00Z</date> <paths> <path action="A">/trunk/Makefile</path> <path action="A">/trunk/hello.c</path> </paths> </logentry> </log>
This particular example shows that the file /trunk/hello.c
was added in revision 2 then modified in revision 3. Revision 2 also saw the addition of /trunk/Makefile
, but this file was not affected by revision 3. The revisions are listed in descending numerical order (equivalent to reverse chronological order).
Suppose you wish to reorganise the log so that entries are grouped by path as opposed to revision number:
<?xml version="1.0"?> <log> <pathentry> <path>/trunk/hello.c</path> <logentry revision="3" action="M" date="2010-12-20T13:15:00Z"/> <logentry revision="2" action="A" date="2010-12-20T12:00:00Z"/> </pathentry> <pathentry> <path>/trunk/Makefile</path> <logentry revision="2" action="A" date="2010-12-20T12:00:00Z"/> </pathentry> </log>
This arrangement could provide a starting point for answering questions such as:
- when was each path originally added to the repository, or
- when was each path most recently modified, or
- how many times has each path been revised.
Methods
Grouping is possible in any version of XSLT, but prior to v2.0 the method is non-obvious and potentially less efficient. You will need to decide whether compatibility with XSLT v1.0 is a requirement. See:
(At the time of writing XSLT v2.0 was supported by Saxon, but not by xsltproc or Xalan.)
Tags: xslt