Reputation: 1
I have the following xml:
<!-- language: lang-xml -->
<Report_Entry>
<Employee_ID> 1 </Employee_ID>
<First_Name>John</First_Name>
<Last_Name>Smith</Last_Name>
<Primary_Address>4200 Holly Hall Street, #18</Primary_Address>
<Hire_Date>2000-01-02-08:00</Hire_Date>
</Report_Entry>
<Report_Entry>
<Employee_ID> 2 </Employee_ID>
<First_Name>Julie</First_Name>
<Last_Name>Ray</Last_Name>
<Primary_Address>255 Gregor Street</Primary_Address>
<Hire_Date>2000-05-01-08:00</Hire_Date>
</Report_Entry>
I have 500 such report entry elements. I want to have the output as:
1, John, Smith, 4200 Holly Hall Street #18, 01-02-2000
2, Julie, Ray, 255 Gregor Street, 05-01-2000
and so on......
Here is the XSLT code that I wrote to transform the above XML:
<!-- language: lang-xslt -->
<xsl:template match="Report_Entry">
<xsl:for-each select="*">
<xsl:value-of select="."/>
<xsl:if test="position() != last()">
<xsl:value-of select="','"/>
</xsl:if>
</xsl:for-each>
<xsl:text> </xsl:text>
</xsl:template>
I am unable to accomplish 2 things:
I would greatly appreciate if anyone can help me out in solving the above two issues.....
Upvotes: 0
Views: 6318
Reputation: 70638
To replace a comma with a space you can make use of the translate function.
<xsl:value-of select="translate(., ',', ' ')"/>
Be wary though, if you have not seen this function before, as it does not work in quite the same way as a normal 'replace' function does. It only translates single characters into other characters. It does not replace matching strings with othe strings. (Note, if you are using XSLT 2.0, there is a 'replace' function available).
As for formatting the date, you could use the substring function here to re-arrage the field, assuming the Hire_Date was always in the same format.
<xsl:value-of select="concat(substring(., 6, 2), '-', substring(., 9, 2), '-' , substring(., 1, 4))"/>
One thing to note, it might be worth re-arranging your XSLT to use templates instead of an xsl:for-each. This would help with writing the code for the Hire_Date as it would be in its own template. Additionally, if Hire_Date was always going to be the last element, this would allow you to drop the xsl:if test on the position.
Try this XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="Report_Entry">
<xsl:apply-templates select="*" />
<xsl:text> </xsl:text>
</xsl:template>
<xsl:template match="Report_Entry/*[not(self::Hire_Date)]">
<xsl:value-of select="translate(., ',', ' ')"/>
<xsl:value-of select="','"/>
</xsl:template>
<xsl:template match="Hire_Date">
<xsl:value-of select="concat(substring(., 6, 2), '-', substring(., 9, 2), '-' , substring(., 1, 4))"/>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1