XSL to transform XML

Get new comments by email
You can cancel email alerts at anytime.
Comments (2)

Bob in Copenhagen, Denmark

76 months ago

Hi
I'm a amateur when it comes to xsl. So any help will be appericiated

I have this XML:
<History>
<ChangeDate>2008-03-07T17:34:02.88+02:00</ChangeDate>
<GroupName>Translation</GroupName>
<UserId>78220198</UserId>
<AuditDataId>4074</AuditDataId>
<ContactName>Jon DVD</ContactName>
<HistoryDetail>
<Field>name</Field>
<OldValue />
<NewValue>Jon</NewValue>
</HistoryDetail>
<HistoryDetail>
<Field>Postal Code</Field>
<OldValue></OldValue>
<NewValue>92012</NewValue>
</HistoryDetail>
</History>

and I would like to transform it to the following.
I want to group all the HistoryDetail nodes under new node "HistoryDetails".

<History>
<ChangeDate>2008-03-07T17:34:02.88+02:00</ChangeDate>
<GroupName>Translation</GroupName>
<UserId>78220198</UserId>
<AuditDataId>4074</AuditDataId>
<ContactName>Jon DVD</ContactName>
<HistoryDetails>
<HistoryDetail>
<Field>name</Field>
<OldValue />
<NewValue>Jon</NewValue>
</HistoryDetail>
<HistoryDetail>
<Field>Postal Code</Field>
<OldValue></OldValue>
<NewValue>92012</NewValue>
</HistoryDetail>
</HistoryDetails>
</History>

I have tried a couple of things without any luck. I always end up coming back to the basic xsl.

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="utf-8"/>

<xsl:template match="@*|node()">
<xsl:if test="not(name()='HistoryDetail')">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:if>
</xsl:template>

</xsl:stylesheet>

/Bob

- Was this comment helpful? Yes / No Reply - Report abuse

Betty Harvey in Glen Burnie, Maryland

76 months ago

This should work for you:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="www.w3.org/1999/XSL/Transform" version="1.0">

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

<xsl:template match="History">
<History>
<xsl:apply-templates/>
<xsl:if test="HistoryDetail">
<HistoryDetails>
<xsl:for-each select="HistoryDetail">
<HistoryDetail>
<xsl:apply-templates/>
</HistoryDetail>
</xsl:for-each>
</HistoryDetails>
</xsl:if>
</History>
</xsl:template>

<xsl:template match="HistoryDetail"/>

</xsl:stylesheet>

- Was this comment helpful? Yes / No Reply - Report abuse

» Sign in or create an account to comment on this topic.