Reputation: 35
I need to dynamically output data from an XML file using XSLT. We have a few different structures of data and rather than have to explicitly loop through each section I was wondering if there is a way to do it in one block of code. This is an example of the XML I will receive:
<IntermediaryInfo>
<PersonalInformation>
<Title>str1234</Title>
<FirstName>str1234</FirstName>
<Surname>str1234</Surname>
<DateofBirth>2012-12-13</DateofBirth>
<WorkTelephoneNumber>str1234</WorkTelephoneNumber>
</PersonalInformation>
<CompanyInformation>
<CompanyName>str1234</CompanyName>
<CompanyFCANumber>str1234</CompanyFCANumber>
</CompanyInformation>
<CompanyAddress>
<PostCode>str1234</PostCode>
<HouseNumber>str1234</HouseNumber>
<HouseName>str1234</HouseName>
<AddressLine1>str1234</AddressLine1>
<AddressLine2>str1234</AddressLine2>
</CompanyAddress>
<CompanyPermissionLevels>
<AdvisingonConsumer>str1234</AdvisingonConsumer>
<ArrangingConsumerBuytoLetmortgageContracts>str1234</ArrangingConsumerBuytoLetmortgageContracts>
</CompanyPermissionLevels>
<PrincipleFirm>
<FirmName>str1234</FirmName>
<FirmFCANumber>123</FirmFCANumber>
</PrincipleFirm>
<LendingPartner>str1234</LendingPartner>
</IntermediaryInfo>
Is there a way to loop through each node and output the node name and value using XSLT? So it would look something like this:
PersonalInformation
-------------------
Title: str1234
FirstName: str1234
Surname: str1234
DateofBirth: 2012-12-13
WorkTelephoneNumber: str1234
CompanyInformation
------------------
CompanyName: str1234
CompanyFCANumber: str1234
Any help would be very much appreciated. Thanks.
Upvotes: 0
Views: 42
Reputation: 117102
Here is something you could use as your starting point:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8" />
<xsl:strip-space elements="*"/>
<xsl:template match="*">
<xsl:param name="indent"/>
<xsl:value-of select="$indent" />
<xsl:value-of select="name()" />
<xsl:text> </xsl:text>
<xsl:apply-templates>
<xsl:with-param name="indent" select="concat($indent, '	')"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="*[text()]">
<xsl:param name="indent"/>
<xsl:value-of select="$indent" />
<xsl:value-of select="name()" />
<xsl:text>: </xsl:text>
<xsl:value-of select="." />
<xsl:text> </xsl:text>
</xsl:template>
</xsl:stylesheet>
Applied to your input example, the result will be:
IntermediaryInfo
PersonalInformation
Title: str1234
FirstName: str1234
Surname: str1234
DateofBirth: 2012-12-13
WorkTelephoneNumber: str1234
CompanyInformation
CompanyName: str1234
CompanyFCANumber: str1234
CompanyAddress
PostCode: str1234
HouseNumber: str1234
HouseName: str1234
AddressLine1: str1234
AddressLine2: str1234
CompanyPermissionLevels
AdvisingonConsumer: str1234
ArrangingConsumerBuytoLetmortgageContracts: str1234
PrincipleFirm
FirmName: str1234
FirmFCANumber: 123
LendingPartner: str1234
Upvotes: 0