I'm stuck finding out how I can access the current node whilst iterating over a collection of nodes with xsL:for-each. This is my XML:
<events>
<event>
<date>
<year>2012</year>
<month>July</month>
</date>
<description>...</description>
</event>
<!-- more events -->
</events>
What I try to achieve is an HTML-representation like this:
<h2>2012</h2>
<dl>
<dt>July</dt>
<dd>One of these for every event with year=2012 and month=July</dd>
<dt>August</dt>
<!-- ... -->
</dl>
<h2>2013</h2>
<!-- ... -->
I'm using an XPath-expression to get all distinct years and then iterate over them calling a template called year with parameters $year and $events. Getting the value for $year is easy, but I'm struggling finding the right events. The following won't work, probably because . in the second predicate refers to the event being tested for the predicate. But how to access the year in there?
<xsl:template match="events">
<xsl:for-each select="event[not(date/year=preceding-sibling::event/date/year)]/date/year">
<xsl:call-template name="year">
<xsl:with-param name="year" select="." />
<xsl:with-param name="events" select="event[date/year=.]" />
</xsl:call-template>
</xsl:for-each>
</xsl:template>
Many thanks in advance!
PS: Must work with XPath and XSLT 1.0.
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="kYear" match="year" use="."/>
<xsl:key name="kEventByMonthYear" match="event"
use="string(date)"/>
<xsl:key name="kMonthByMonthYear" match="month"
use="string(..)"/>
<xsl:key name="kMonthByYear" match="month"
use="../year"/>
<xsl:template match="/*">
<xsl:for-each select=
"*/date/year
[generate-id() = generate-id(key('kYear', .)[1])]
">
<h2><xsl:value-of select="."/></h2>
<dl>
<xsl:apply-templates select=
"key('kMonthByYear', current())
[generate-id()
=
generate-id(key('kMonthByMonthYear',
string(..)
)[1]
)
]"/>
</dl>
</xsl:for-each>
</xsl:template>
<xsl:template match="month">
<dt><xsl:value-of select="."/></dt>
<xsl:for-each select=
"key('kEventByMonthYear', string(current()/..))">
<dd><xsl:value-of select="description"/></dd>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
when applied on the following XML document:
<events>
<event>
<date>
<year>2012</year>
<month>January</month>
</date>
<description>Jan1</description>
</event>
<event>
<date>
<year>2012</year>
<month>January</month>
</date>
<description>Jan2</description>
</event>
<event>
<date>
<year>2012</year>
<month>March</month>
</date>
<description>Mar1</description>
</event>
<event>
<date>
<year>2012</year>
<month>March</month>
</date>
<description>Mar2</description>
</event>
<event>
<date>
<year>2012</year>
<month>March</month>
</date>
<description>Mar3</description>
</event>
<event>
<date>
<year>2012</year>
<month>July</month>
</date>
<description>Jul1</description>
</event>
<event>
<date>
<year>2012</year>
<month>July</month>
</date>
<description>Jul2</description>
</event>
<event>
<date>
<year>2012</year>
<month>September</month>
</date>
<description>Sep1</description>
</event>
<event>
<date>
<year>2012</year>
<month>October</month>
</date>
<description>Oct1</description>
</event>
<event>
<date>
<year>2012</year>
<month>October</month>
</date>
<description>Oct2</description>
</event>
<event>
<date>
<year>2012</year>
<month>November</month>
</date>
<description>Nov1</description>
</event>
<event>
<date>
<year>2012</year>
<month>November</month>
</date>
<description>Nov2</description>
</event>
<event>
<date>
<year>2012</year>
<month>December</month>
</date>
<description>Dec1</description>
</event>
<event>
<date>
<year>2012</year>
<month>December</month>
</date>
<description>Dec2</description>
</event>
<event>
<date>
<year>2012</year>
<month>December</month>
</date>
<description>Dec3</description>
</event>
<event>
<date>
<year>2013</year>
<month>January</month>
</date>
<description>Jan1</description>
</event>
<event>
<date>
<year>2013</year>
<month>January</month>
</date>
<description>Jan2</description>
</event>
</events>
produces the wanted, correct result:
<h2>2012</h2>
<dl>
<dt>January</dt>
<dd>Jan1</dd>
<dd>Jan2</dd>
<dt>March</dt>
<dd>Mar1</dd>
<dd>Mar2</dd>
<dd>Mar3</dd>
<dt>July</dt>
<dd>Jul1</dd>
<dd>Jul2</dd>
<dt>September</dt>
<dd>Sep1</dd>
<dt>October</dt>
<dd>Oct1</dd>
<dd>Oct2</dd>
<dt>November</dt>
<dd>Nov1</dd>
<dd>Nov2</dd>
<dt>December</dt>
<dd>Dec1</dd>
<dd>Dec2</dd>
<dd>Dec3</dd>
</dl>
<h2>2013</h2>
<dl>
<dt>January</dt>
<dd>Jan1</dd>
<dd>Jan2</dd>
</dl>
Explanation:
Proper use of the Muenchian method for grouping -- with composite grouping keys.
#Dimitre Novatchev's answer is the more elaborate one, but I found another possibility I'd like to share. It doesn't depend on keys and therefore is a bit more "newbie-friendly". On the other hand it too doesn't solve the original "accessing current node of an iteration" problem:
<?xml version="1.0" encoding="utf-8"?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="events">
<xsl:for-each select="event[not(date/year=preceding-sibling::event/date/year)]/date/year">
<xsl:call-template name="year">
<xsl:with-param name="year" select="." />
</xsl:call-template>
</xsl:for-each>
</xsl:template>
<xsl:template name="year">
<xsl:param name="year" />
<h2><xsl:value-of select="$year" /></h2>
<dl class="dl-horizontal">
<xsl:for-each select="//event[date/year=$year][not(date/month=preceding-sibling::event[date/year=$year]/date/month)]/date/month">
<xsl:call-template name="month">
<xsl:with-param name="month" select="." />
<xsl:with-param name="year" select="$year" />
</xsl:call-template>
</xsl:for-each>
</dl>
</xsl:template>
<xsl:template name="month">
<xsl:param name="month" />
<xsl:param name="year" />
<dt><xsl:value-of select="$month" /></dt>
<xsl:for-each select="//event[date/year=$year][date/month=$month]">
<xsl:call-template name="event">
<xsl:with-param name="event" select="." />
</xsl:call-template>
</xsl:for-each>
</xsl:template>
<xsl:template name="event">
<xsl:param name="event" />
<dd><xsl:copy-of select="description/node()" /></dd>
</xsl:template>
</xsl:transform>
Related
I have the following XML:
<data>
<request method="PUT">
<context>
<record_count>5</record_count>
<record_type>Customer</record_type>
</context>
<value>
<company>ABC</company>
<customer>Contoso</customer>
</value>
<value>
<company>ABC</company>
<customer>Forest</customer>
</value>
<value>
<company>XYZ</company>
<customer>Forest</customer>
</value>
<value>
<company>XYZ</company>
<customer>Cave</customer>
</value>
<value>
<company>ABC</company>
<customer>Cave</customer>
</value>
</request>
</data>
and the following transformation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="company-key" match="value" use="company"/>
<xsl:template match="#*|node()">
<xsl:copy>
<xsl:apply-templates select="#*" />
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
<xsl:template match="/data/request/value" />
<xsl:template match="/data/request/value[count(. | key('company-key', company)[1]) = 1]">
<xsl:element name="group">
<xsl:attribute name="company">
<xsl:value-of select="company"/>
</xsl:attribute>
<xsl:attribute name="method">
<xsl:value-of select="/data/request/#method"/>
</xsl:attribute>
<xsl:attribute name="record-type">
<xsl:value-of select="/data/request/context/record_type"/>
</xsl:attribute>
<xsl:for-each select="key('company-key', company)">
<xsl:copy>
<xsl:apply-templates select="#*|node()"/>
</xsl:copy>
</xsl:for-each>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
The transformation groups the data in the value nodes into new nodes.
The name of these nodes is group and they have their own attributes.
This works correctly and the ouput looks like this:
<data>
<request method="PUT">
<context>
<record_count>5</record_count>
<record_type>Customer</record_type>
</context>
<group company="ABC" method="PUT" record-type="Customer">
<value>
<company>ABC</company>
<customer>Contoso</customer>
</value>
<value>
<company>ABC</company>
<customer>Forest</customer>
</value>
<value>
<company>ABC</company>
<customer>Cave</customer>
</value>
</group>
<group company="XYZ" method="PUT" record-type="Customer">
<value>
<company>XYZ</company>
<customer>Forest</customer>
</value>
<value>
<company>XYZ</company>
<customer>Cave</customer>
</value>
</group>
</request>
</data>
The problem I have is that I cannot create a transformation that prepares the data as described and then moves all the "group" nodes to parent "data" node and removes the old "request" node.
All this in one transformation.
The output should look like this:
<data>
<group company="ABC" method="PUT" record-type="Customer">
<value>
<company>ABC</company>
<customer>Contoso</customer>
</value>
<value>
<company>ABC</company>
<customer>Forest</customer>
</value>
<value>
<company>ABC</company>
<customer>Cave</customer>
</value>
</group>
<group company="XYZ" method="PUT" record-type="Customer">
<value>
<company>XYZ</company>
<customer>Forest</customer>
</value>
<value>
<company>XYZ</company>
<customer>Cave</customer>
</value>
</group>
</data>
How about simply:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="company-key" match="value" use="company"/>
<xsl:template match="/data">
<xsl:variable name="method" select="request/#method" />
<xsl:variable name="record_type" select="request/context/record_type" />
<data>
<xsl:for-each select="request/value[count(. | key('company-key', company)[1]) = 1]">
<group company="{company}" method="{$method}" record-type="{$record_type}">
<xsl:copy-of select="key('company-key', company)"/>
</group>
</xsl:for-each>
</data>
</xsl:template>
</xsl:stylesheet>
Note that this assumes that data contains only one request.
I'm new to XSL and i'm trying to copy a node of XML to another node in the same XML using XSLT. I can able to transform the file as expected but the XMLNS attribute is getting added to the destination which I don't want.
I have tried all the option of copy-namespaces='no' using XSLT2.0 but that doesn't work. Also, I cant have a prefix of namespaces in the XSLT and use exclude namespaces to avoid xmlns because the incoming XML file is dynamic and namespaces keep on changing. I can't have all the namespaces declared as a prefix in XSLT.
Incoming XML:
<?xml version="1.0" encoding="UTF-8"?>
<PropertySet>
<Message>
<NotificationHeader>
<BusinessId></BusinessId>
<CorrelationId>0201201916:21:24CKG3N</CorrelationId>
<SourceName></SourceName>
<SourceId></SourceId>
<EventType></EventType>
<SecurityIdentifierId></SecurityIdentifierId>
<ClientRequestId></ClientRequestId>
<TargetId>ESB</TargetId>
<EventTime></EventTime>
<RequestUser></RequestUser>
</NotificationHeader>
<EventList>
<Event>
<PayLoad>
<ListOfActionIo xmlns="http://www.test.com/IO">
<Action>
<ActivityId>4-309C7WV</ActivityId>
<ActivitySRId></ActivitySRId>
<ActivityTemplateId></ActivityTemplateId>
<ActivityUID>4-309C7WV</ActivityUID>
<Category> Notification</Category>
<Comment></Comment>
<Type>Action</Type>
<ListOfDestination>
<Destination>
<DestinationName>NSW Aboriginal Education Consultative Group Incorporated</DestinationName>
</Destination>
<Destination>
<DestinationName>NSW Aboriginal Education Consultative Group Incorporated</DestinationName>
</Destination>
</ListOfDestination>
</Action>
</ListOfActionIo>
</PayLoad>
</Event>
</EventList>
<DestinationList>
<Destination>
<DestinationName></DestinationName>
<DestinationId></DestinationId>
</Destination>
</DestinationList>
</Message>
</PropertySet>
XSLT Code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml" encoding="UTF-8"/>
<xsl:strip-space elements="*"/>
<xsl:template match="#*|node()">
<xsl:copy>
<xsl:apply-templates select="#*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="//*[name()='Message']/*[name()='DestinationList']//*[name()='Destination']"></xsl:template>
<!--Copy the destination from one node to another node-->
<xsl:template match="//*[name()='Message']/*[name()='DestinationList']">
<xsl:copy>
<xsl:copy-of select="//*[name()='Message']/*[name()='EventList']//*[name()='Destination']"/>
</xsl:copy>
</xsl:template>
<!--Remove the original node from where the destination was copied-->
<xsl:template match="//*[name()='Message']/*[name()='EventList']//*[name()='ListOfDestination']"></xsl:template>
</xsl:stylesheet>
Output:
<PropertySet>
<Message>
<NotificationHeader>
<BusinessId/>
<CorrelationId>0201201916:21:24CKG3N</CorrelationId>
<SourceName/>
<SourceId/>
<EventType/>
<SecurityIdentifierId/>
<ClientRequestId/>
<TargetId>ESB</TargetId>
<EventTime/>
<RequestUser/>
</NotificationHeader>
<EventList>
<Event>
<PayLoad>
<ListOfActionIo xmlns="http://www.test.com/IO">
<Action>
<ActivityId>4-309C7WV</ActivityId>
<ActivitySRId/>
<ActivityTemplateId/>
<ActivityUID>4-309C7WV</ActivityUID>
<Category> Notification</Category>
<Comment/>
<Type>Action</Type>
</Action>
</ListOfActionIo>
</PayLoad>
</Event>
</EventList>
<DestinationList>
<Destination xmlns="http://www.test.com/IO">
<DestinationName>NSW Aboriginal Education Consultative Group Incorporated</DestinationName>
</Destination>
<Destination xmlns="http://www.test.com/IO">
<DestinationName>NSW Aboriginal Education Consultative Group Incorporated</DestinationName>
</Destination>
</DestinationList>
</Message>
</PropertySet>
Expected Output:
Without the Namespaces on the copied node.
<PropertySet>
<Message>
<NotificationHeader>
<BusinessId/>
<CorrelationId>0201201916:21:24CKG3N</CorrelationId>
<SourceName/>
<SourceId/>
<EventType/>
<SecurityIdentifierId/>
<ClientRequestId/>
<TargetId>ESB</TargetId>
<EventTime/>
<RequestUser/>
</NotificationHeader>
<EventList>
<Event>
<PayLoad>
<ListOfActionIo xmlns="http://www.test.com/IO">
<Action>
<ActivityId>4-309C7WV</ActivityId>
<ActivitySRId/>
<ActivityTemplateId/>
<ActivityUID>4-309C7WV</ActivityUID>
<Category> Notification</Category>
<Comment/>
<Type>Action</Type>
</Action>
</ListOfActionIo>
</PayLoad>
</Event>
</EventList>
<DestinationList>
<Destination>
<DestinationName>NSW Aboriginal Education Consultative Group Incorporated</DestinationName>
</Destination>
<Destination>
<DestinationName>NSW Aboriginal Education Consultative Group Incorporated</DestinationName>
</Destination>
</DestinationList>
</Message>
</PropertySet>
You are asking the wrong question. You don't want to "remove namespaces" - you want to change the namespace of transformed elements. This is akin to renaming the elements.
Now, since your example is confusing (and too long), consider the following:
XML
<root>
<colors>
<color>red</color>
<color>blue</color>
</colors>
<shapes xmlns="some-unknown-namespace">
<shape>circle</shape>
<shape>square</shape>
</shapes>
<sizes>
<size>small</size>
<size>large</size>
</sizes>
</root>
To change the namespace of shapes (and its descendants, that inherit it!) to no-namespace, without knowing in advance what the original namespace will be, you can do:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="#*|node()">
<xsl:copy>
<xsl:apply-templates select="#*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[ancestor-or-self::*[name()='shapes']]">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="#*|node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Result
<?xml version="1.0" encoding="UTF-8"?>
<root>
<colors>
<color>red</color>
<color>blue</color>
</colors>
<shapes>
<shape>circle</shape>
<shape>square</shape>
</shapes>
<sizes>
<size>small</size>
<size>large</size>
</sizes>
</root>
Added:
lets modify the code to move the shapes into sizes and remove the shapes node.
OK, let's do that:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="#*|node()">
<xsl:copy>
<xsl:apply-templates select="#*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="sizes">
<xsl:copy>
<xsl:apply-templates/>
<!-- move the shapes into sizes -->
<xsl:apply-templates select="../*[name()='shapes']/*"/>
</xsl:copy>
</xsl:template>
<!-- remove the shapes element -->
<xsl:template match="*[name()='shapes']"/>
<xsl:template match="*[ancestor::*[name()='shapes']]">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="#*|node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Result
<?xml version="1.0" encoding="UTF-8"?>
<root>
<colors>
<color>red</color>
<color>blue</color>
</colors>
<sizes>
<size>small</size>
<size>large</size>
<shape>circle</shape>
<shape>square</shape>
</sizes>
</root>
I need to convert a name value pair into XML. I'm able to generate an XML, but the element name should be grouped and it should not be duplicated. Please see below. The FieldValue element contains 2 OrderItem values in the Detail node. If the FieldValue with OrderItem repeats, then the result should be grouped into one OrderItem node. Please help.
Source XML:
<SC>
<Header>
<Record>
<FieldName>Schema</FieldName>
<FieldValue>OrderHeader</FieldValue>
</Record>
<Record>
<FieldName>Order</FieldName>
<FieldValue>1234</FieldValue>
</Record>
</Header>
<Detail>
<Record>
<FieldName>Schema</FieldName>
<FieldValue>OrderItem</FieldValue>
</Record>
<Record>
<FieldName>Item</FieldName>
<FieldValue>1</FieldValue>
</Record>
<Record>
<FieldName>Qty</FieldName>
<FieldValue>10</FieldValue>
</Record>
</Detail>
<Detail>
<Record>
<FieldName>Schema</FieldName>
<FieldValue>OrderItem</FieldValue>
</Record>
<Record>
<FieldName>Item</FieldName>
<FieldValue>2</FieldValue>
</Record>
<Record>
<FieldName>Qty</FieldName>
<FieldValue>20</FieldValue>
</Record>
</Detail>
</SC>
Target XML:
<Order>
<OrderItem>
<Item>
<Item>1</Item>
<Qty>10</Qty>
</Item>
<Item>
<Item>2</Item>
<Qty>20</Qty>
</Item>
</OrderItem>
</Order>
XSLT:
<xsl:template match="#*|node()">
<Order>
<xsl:for-each select="Detail">
<Item>
<xsl:apply-templates select="Record[position()>1]"/>
</Item>
</xsl:for-each>
</Order>
</xsl:template>
<xsl:template match="Record">
<xsl:element name="{FieldName}">
<xsl:value-of select="FieldValue"/>
</xsl:element>
</xsl:template>
The grouping can be done as follows:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">
<xsl:output indent="yes"/>
<xsl:template match="SC">
<Order>
<xsl:for-each-group select="Detail" group-by="Record[1]/FieldValue">
<xsl:element name="{current-grouping-key()}">
<xsl:apply-templates select="current-group()"/>
</xsl:element>
</xsl:for-each-group>
</Order>
</xsl:template>
<xsl:template match="Detail">
<Item>
<xsl:apply-templates select="Record[position() gt 1]"/>
</Item>
</xsl:template>
<xsl:template match="Record">
<xsl:element name="{FieldName}">
<xsl:value-of select="FieldValue"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
It appears that you are trying to define two XSLT templates, when one should be sufficient. You want to match on the root and then that you want to iterate over each SC/Detail.
Then, you want to take the FieldValue of the sibling of the FieldName node that is 'Item' (for item value) and 'Qty' (for quantity value), but only those listed under 'Record'.
Note: You have specified a doubly-nested <Item> in your transformed output and this solution reflects that requirement.
This XSLT should do what you are requesting:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<xsl:for-each select="SC/Detail">
<Order>
<OrderItem>
<Item>
<Item>
<xsl:value-of select="Record[FieldName[text()='Item']]/FieldValue" />
</Item>
<Qty>
<xsl:value-of select="Record[FieldName[text()='Qty']]/FieldValue" />
</Qty>
</Item>
</OrderItem>
</Order>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
I have a document of following structure (this is just an example to help me verbalize the problem), that I'm trying to flatten. By flattening I mean copying all the <Report_Entry> nodes with several <Event>s so that each <Report_Entry> node contained just a single <Event>
What I have:
<?xml version="1.0"?>
<Report_Data>
<Report_Entry>
<ID>1</ID>
<Event>
<Start_Date>2011-09-06</Start_Date>
<End_Date>2011-09-10</End_Date>
</Event>
<Event>
<Start_Date>2011-09-10</Start_Date>
<End_Date>2011-09-15</End_Date>
</Event>
<Event>
<Start_Date>2011-09-15</Start_Date>
<End_Date>2011-09-20</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>2</ID>
<Event>
<Start_Date>2011-09-20</Start_Date>
<End_Date>2011-09-25</End_Date>
</Event>
<Event>
<Start_Date>2011-09-25</Start_Date>
<End_Date>2011-09-30</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>3</ID>
<Event>
<Start_Date>2011-09-30</Start_Date>
<End_Date>2011-10-05</End_Date>
</Event>
</Report_Entry>
</Report_Data>
What I'm trying to get:
<?xml version="1.0"?>
<Report_Data>
<Report_Entry>
<ID>1</ID>
<Event>
<Start_Date>2011-09-06</Start_Date>
<End_Date>2011-09-10</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>1</ID>
<Event>
<Start_Date>2011-09-10</Start_Date>
<End_Date>2011-09-15</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>1</ID>
<Event>
<Start_Date>2011-09-15</Start_Date>
<End_Date>2011-09-20</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>2</ID>
<Event>
<Start_Date>2011-09-20</Start_Date>
<End_Date>2011-09-25</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>2</ID>
<Event>
<Start_Date>2011-09-25</Start_Date>
<End_Date>2011-09-30</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>3</ID>
<Event>
<Start_Date>2011-09-30</Start_Date>
<End_Date>2011-10-05</End_Date>
</Event>
</Report_Entry>
</Report_Data>
Here is XSLT that I'm using:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node() | #*">
<xsl:copy>
<xsl:apply-templates select="node() | #*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Report_Entry">
<xsl:for-each select="Event">
<Report_Entry>
<xsl:copy-of select="../*[not(self::Event)]"/>
<xsl:copy-of select="."/>
</Report_Entry>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
It works, though I feel that there might be a better, faster and more universal solution. In particular, I don't like "hardcoding" <Report_Entry> since this way I wouldn't be able to copy its attributes (if any). Are there other ways/templates to deal with this problem?
As simple as this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/*">
<Report_Data>
<xsl:apply-templates select="*/Event"/>
</Report_Data>
</xsl:template>
<xsl:template match="Event">
<Report_Entry>
<xsl:copy-of select="../ID | ."/>
</Report_Entry>
</xsl:template>
</xsl:stylesheet>
When this transformation is applied on the provided XML document:
<Report_Data>
<Report_Entry>
<ID>1</ID>
<Event>
<Start_Date>2011-09-06</Start_Date>
<End_Date>2011-09-10</End_Date>
</Event>
<Event>
<Start_Date>2011-09-10</Start_Date>
<End_Date>2011-09-15</End_Date>
</Event>
<Event>
<Start_Date>2011-09-15</Start_Date>
<End_Date>2011-09-20</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>2</ID>
<Event>
<Start_Date>2011-09-20</Start_Date>
<End_Date>2011-09-25</End_Date>
</Event>
<Event>
<Start_Date>2011-09-25</Start_Date>
<End_Date>2011-09-30</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>3</ID>
<Event>
<Start_Date>2011-09-30</Start_Date>
<End_Date>2011-10-05</End_Date>
</Event>
</Report_Entry>
</Report_Data>
the wanted, correct result is produced:
<Report_Data>
<Report_Entry>
<ID>1</ID>
<Event>
<Start_Date>2011-09-06</Start_Date>
<End_Date>2011-09-10</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>1</ID>
<Event>
<Start_Date>2011-09-10</Start_Date>
<End_Date>2011-09-15</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>1</ID>
<Event>
<Start_Date>2011-09-15</Start_Date>
<End_Date>2011-09-20</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>2</ID>
<Event>
<Start_Date>2011-09-20</Start_Date>
<End_Date>2011-09-25</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>2</ID>
<Event>
<Start_Date>2011-09-25</Start_Date>
<End_Date>2011-09-30</End_Date>
</Event>
</Report_Entry>
<Report_Entry>
<ID>3</ID>
<Event>
<Start_Date>2011-09-30</Start_Date>
<End_Date>2011-10-05</End_Date>
</Event>
</Report_Entry>
</Report_Data>
Your answer couldn't be much simpler, so no need to worry on that front. When writing code, but especially XSLT, the clarity of the code tends to be worth a lot more than its ultimate efficiency.
As for the hardcoded element name and copying attributes, here's a start:
<xsl:template match="Report_Entry">
<xsl:variable name="parent-name" select="name()"/>
<xsl:variable name="parent-attributes" select="#*"/>
<xsl:for-each select="Event">
<xsl:element name="{$parent-name}">
<xsl:copy-of select="$parent-attributes"/>
<xsl:copy-of select="../*[not(self::Event)]"/>
<xsl:copy-of select="."/>
</xsl:element>
</xsl:for-each>
</xsl:template>
variables are used to stash some of the context as it exists outside the for-each. element makes an element that's a look-alike for your original, no matter what it's called, and the first copy-of makes it more convincing by copying in the original's attributes as well. Now, if your data suddenly takes on attributes, you'll be ready.
The non-hardcodedness of the name doesn't mean much in this case, but it would if, say, you were to factor out that part to a separate template and call it from multiple places:
<xsl:template name="collapse-the-thing">
<xsl:param name="context"/>
<xsl:param name="sub-element-name" select="'Event'"/>
<xsl:variable name="parent-name" select="name($context)"/>
<xsl:variable name="parent-attributes" select="$context/#*"/>
<xsl:for-each select="$context/*[name()=$sub-element-name]">
<xsl:element name="{$parent-name}">
<xsl:copy-of select="$parent-attributes"/>
<xsl:copy-of select="../*[name()!=$sub-element-name]"/>
<xsl:copy-of select="."/>
</xsl:element>
</xsl:for-each>
</xsl:template>
<xsl:template match="Report_Entry">
<xsl:call-template name="collapse-the-thing">
<xsl:with-param name="context" select="."/>
</xsl:call-template>
</xsl:template>
<xsl:template match="Some_Other_Entry">
<xsl:call-template name="collapse-the-thing">
<xsl:with-param name="context" select="."/>
<xsl:param name="sub-element-name" select="'Happening'"/>
</xsl:call-template>
</xsl:template>
Hope that was enlightening. Enjoy!
I'm relatively new to XSL and am attempting to elegantly transform a Google Calendar feed into something more readable.
I would appreciate your eyes on whether there are optimizations to be made. In particular, I would like your advice on template use. I've read a lot about how for-each is not appropriate to use willy-nilly (rather, one should attempt to make judicious use of templates).
Thank you very much.
Original XML (showing only one event):
<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gCal='http://schemas.google.com/gCal/2005' xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://www.google.com/calendar/feeds/bachya1208%40gmail.com/public/full</id>
<updated>2011-09-19T21:32:50.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'/>
<title type='text'>John Doe</title>
<subtitle type='text'>John Doe</subtitle>
<link rel='alternate' type='text/html' href='https://www.google.com/calendar/embed?src=bachya1208#gmail.com'/>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full'/>
<link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml' href='https://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full/batch'/>
<link rel='self' type='application/atom+xml' href='https://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full?max-results=25'/>
<link rel='next' type='application/atom+xml' href='https://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full?start-index=26&max-results=25'/>
<author>
<name>John Doe</name>
<email>johndoe#gmail.com</email>
</author>
<generator version='1.0' uri='http://www.google.com/calendar'>Google Calendar</generator>
<openSearch:totalResults>1334</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<gCal:timezone value='America/Denver'/>
<gCal:timesCleaned value='0'/>
<entry>
<id>http://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full/lp0upnpndnkp0ruqht7ef84kds</id>
<published>2011-09-14T21:15:16.000Z</published>
<updated>2011-09-14T21:15:16.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'/>
<title type='text'>Oil Change</title>
<content type='text'/>
<link rel='alternate' type='text/html' href='https://www.google.com/calendar/event?eid=bHAwdXBucG5kbmtwMHJ1cWh0N2VmODRrZHMgYmFjaHlhMTIwOEBt' title='alternate'/>
<link rel='self' type='application/atom+xml' href='https://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full/lp0upnpndnkp0ruqht7ef84kds'/>
<author>
<name>John Doe</name>
<email>johndoe#gmail.com</email>
</author>
<gd:comments>
<gd:feedLink href='https://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full/lp0upnpndnkp0ruqht7ef84kds/comments'/>
</gd:comments>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'/>
<gd:where valueString='9955 E Arapahoe Road, Englewood, CO 80112 (Go Subaru Arapahoe)'/>
<gd:who email='johndoe#gmail.com' rel='http://schemas.google.com/g/2005#event.organizer' valueString='bachya1208#gmail.com'/>
<gd:when endTime='2011-09-29T11:30:00.000-06:00' startTime='2011-09-29T10:30:00.000-06:00'/>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'/>
<gCal:anyoneCanAddSelf value='false'/>
<gCal:guestsCanInviteOthers value='true'/>
<gCal:guestsCanModify value='false'/>
<gCal:guestsCanSeeGuests value='true'/>
<gCal:sequence value='0'/>
<gCal:uid value='lp0upnpndnkp0ruqht7ef84kds#google.com'/>
</entry>
</feed>
XSLT:
<?xml version="1.0"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template name="formatDateTime">
<xsl:param name="dateTime" />
<xsl:value-of select="concat(substring-before($dateTime, 'T'), ' ', substring-before(substring-after($dateTime, 'T'), '.'))" />
</xsl:template>
<xsl:template match="/">
<Events>
<xsl:apply-templates select="/*/*[local-name()= 'entry']" />
</Events>
</xsl:template>
<xsl:template match="*[local-name()= 'entry']">
<xsl:variable name="startDateTime" select="*[name() = 'gd:when']/#*[local-name() = 'startTime']" />
<xsl:variable name="endDateTime" select="*[name() = 'gd:when']/#*[local-name() = 'endTime']" />
<Event>
<EventTitle>
<xsl:value-of select="*[local-name() = 'title'][1]" />
</EventTitle>
<StartDateTime>
<xsl:call-template name="formatDateTime">
<xsl:with-param name="dateTime" select="$startDateTime" />
</xsl:call-template>
</StartDateTime>
<EndDateTime>
<xsl:call-template name="formatDateTime">
<xsl:with-param name="dateTime" select="$endDateTime" />
</xsl:call-template>
</EndDateTime>
<Who>
<xsl:value-of select="*[local-name() = 'author']/*[local-name() = 'name']" />
</Who>
<Where>
<xsl:value-of select="*[name() = 'gd:where']/#*[local-name() = 'valueString']" />
</Where>
<Status>
<xsl:value-of select="*[name() = 'gd:eventStatus']/#*[local-name() = 'value']" />
</Status>
</Event>
</xsl:template>
</xsl:stylesheet>
Output:
<?xml version="1.0" encoding="UTF-16"?>
<Events>
<Event>
<EventTitle>Oil Change</EventTitle>
<StartDateTime>2011-09-29 10:30:00</StartDateTime>
<EndDateTime>2011-09-29 11:30:00</EndDateTime>
<Who>John Doe</Who>
<Where>9955 E Arapahoe Road, Englewood, CO 80112 (Go Subaru Arapahoe)</Where>
<Status>http://schemas.google.com/g/2005#event.confirmed</Status>
</Event>
</Events>
Your approach looks fine to me. I think your XPath code would be much cleaner and would probably run faster if you used regular element selection instead of local-name. The reason you probably struggled with your XPath was because you're consuming XML that has a default namespace of http://www.w3.org/2005/Atom, and that namespace isn't declared in your stylesheet. Here's a snippet of how a more simplified stylesheet could look, using an f: prefix for the feed namespace:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://www.w3.org/2005/Atom"
xmlns:gd="http://schemas.google.com/g/2005">
<!-- ... -->
<xsl:template match="/">
<Events>
<xsl:apply-templates select="//f:entry" />
</Events>
</xsl:template>
<xsl:template match="f:entry">
<xsl:variable name="startDateTime" select="gd:when/#startTime" />
<xsl:variable name="endDateTime" select="gd:when/#endTime" />
<Event>
<EventTitle>
<xsl:value-of select="f:title[1]" />
</EventTitle>
<StartDateTime>
<xsl:call-template name="formatDateTime">
<xsl:with-param name="dateTime" select="$startDateTime" />
</xsl:call-template>
</StartDateTime>
<EndDateTime>
<xsl:call-template name="formatDateTime">
<xsl:with-param name="dateTime" select="$endDateTime" />
</xsl:call-template>
</EndDateTime>
<Who>
<xsl:value-of select="f:author/f:name" />
</Who>
<Where>
<xsl:value-of select="gd:where/#valueString" />
</Where>
<Status>
<xsl:value-of select="gd:eventStatus/#value" />
</Status>
</Event>
</xsl:template>
<!-- etc -->
</xsl:stylesheet>
I would be inclined to replace the formatDateTime template with a match template:
<xsl:template match="#*" mode="formatDateTime">
<xsl:value-of select="concat(substring-before(., 'T'),
' ', substring-before(substring-after(., 'T'), '.'))" />
</xsl:template>
and change the calls to
<StartDateTime>
<xsl:apply-templates select="$startDateTime" mode="formatDateTime"/>
</StartDateTime>
<EndDateTime>
<xsl:apply-templates select="$endDateTime" mode="formatDateTime"/>
</EndDateTime>
Just because the call-template syntax is so verbose.
(and I would probably inline the variables too - they don't see to add value).
Here is a complete transformation that is derived from the provided, solving the default namespace problem (as already done by #Jacob), but also completely eliminating the unnecessary template matching the document node (/) and assuring that two unwanted namespaces will not appear on every (literal result) element in the output:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:a="http://www.w3.org/2005/Atom"
xmlns:gd="http://schemas.google.com/g/2005"
exclude-result-prefixes="a gd">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="a:entry[1]">
<Events>
<xsl:apply-templates select="../a:entry" mode="process"/>
</Events>
</xsl:template>
<xsl:template match="a:entry" mode="process">
<xsl:variable name="startDateTime" select="gd:when/#startTime" />
<xsl:variable name="endDateTime" select="gd:when/#endTime" />
<Event>
<EventTitle>
<xsl:value-of select="a:title[1]" />
</EventTitle>
<StartDateTime>
<xsl:call-template name="formatDateTime">
<xsl:with-param name="dateTime" select="$startDateTime" />
</xsl:call-template>
</StartDateTime>
<EndDateTime>
<xsl:call-template name="formatDateTime">
<xsl:with-param name="dateTime" select="$endDateTime" />
</xsl:call-template>
</EndDateTime>
<Who>
<xsl:value-of select="a:author/a:name" />
</Who>
<Where>
<xsl:value-of select="gd:where/#valueString" />
</Where>
<Status>
<xsl:value-of select="gd:eventStatus/#value" />
</Status>
</Event>
</xsl:template>
<xsl:template name="formatDateTime">
<xsl:param name="dateTime" />
<xsl:value-of select="concat(substring-before($dateTime, 'T'), ' ', substring-before(substring-after($dateTime, 'T'), '.'))" />
</xsl:template>
<xsl:template match="text()|a:entry"/>
</xsl:stylesheet>
When this transformation is applied on the provided XML document:
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gCal='http://schemas.google.com/gCal/2005' xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://www.google.com/calendar/feeds/bachya1208%40gmail.com/public/full</id>
<updated>2011-09-19T21:32:50.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'/>
<title type='text'>John Doe</title>
<subtitle type='text'>John Doe</subtitle>
<link rel='alternate' type='text/html' href='https://www.google.com/calendar/embed?src=bachya1208#gmail.com'/>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full'/>
<link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml' href='https://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full/batch'/>
<link rel='self' type='application/atom+xml' href='https://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full?max-results=25'/>
<link rel='next' type='application/atom+xml' href='https://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full?start-index=26&max-results=25'/>
<author>
<name>John Doe</name>
<email>johndoe#gmail.com</email>
</author>
<generator version='1.0' uri='http://www.google.com/calendar'>Google Calendar</generator>
<openSearch:totalResults>1334</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<gCal:timezone value='America/Denver'/>
<gCal:timesCleaned value='0'/>
<entry>
<id>http://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full/lp0upnpndnkp0ruqht7ef84kds</id>
<published>2011-09-14T21:15:16.000Z</published>
<updated>2011-09-14T21:15:16.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'/>
<title type='text'>Oil Change</title>
<content type='text'/>
<link rel='alternate' type='text/html' href='https://www.google.com/calendar/event?eid=bHAwdXBucG5kbmtwMHJ1cWh0N2VmODRrZHMgYmFjaHlhMTIwOEBt' title='alternate'/>
<link rel='self' type='application/atom+xml' href='https://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full/lp0upnpndnkp0ruqht7ef84kds'/>
<author>
<name>John Doe</name>
<email>johndoe#gmail.com</email>
</author>
<gd:comments>
<gd:feedLink href='https://www.google.com/calendar/feeds/johndoe%40gmail.com/public/full/lp0upnpndnkp0ruqht7ef84kds/comments'/>
</gd:comments>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'/>
<gd:where valueString='9955 E Arapahoe Road, Englewood, CO 80112 (Go Subaru Arapahoe)'/>
<gd:who email='johndoe#gmail.com' rel='http://schemas.google.com/g/2005#event.organizer' valueString='bachya1208#gmail.com'/>
<gd:when endTime='2011-09-29T11:30:00.000-06:00' startTime='2011-09-29T10:30:00.000-06:00'/>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'/>
<gCal:anyoneCanAddSelf value='false'/>
<gCal:guestsCanInviteOthers value='true'/>
<gCal:guestsCanModify value='false'/>
<gCal:guestsCanSeeGuests value='true'/>
<gCal:sequence value='0'/>
<gCal:uid value='lp0upnpndnkp0ruqht7ef84kds#google.com'/>
</entry>
</feed>
the wanted, correct result is produced:
<Events>
<Event>
<EventTitle>Oil Change</EventTitle>
<StartDateTime>2011-09-29 10:30:00</StartDateTime>
<EndDateTime>2011-09-29 11:30:00</EndDateTime>
<Who>John Doe</Who>
<Where>9955 E Arapahoe Road, Englewood, CO 80112 (Go Subaru Arapahoe)</Where>
<Status>http://schemas.google.com/g/2005#event.confirmed</Status>
</Event>
</Events>