I am trying to convert attrivbute value to node in new xml
Example: Input Xml:
<?xml version="1.0" encoding="UTF-8"?>
<filecontent>
<work>
<Field name="Content Title">Title1</Field>
<Field name="Job Opening">Job Value</Field>
<Field name="Date Opened">Date Opened Value</Field>
<Field name="Place">Place Value</Field>
</work>
</filecontent>
Output Xml need as below:
<filecontent>
<work>
<ContentTitle>Title1</ContentTitle>
<JobOpening>Job Value</JobOpening>
<DateOpened>Date Opened Value</DateOpened>
<Place>Industry Value</Place>
</work>
</filecontent>
And what every value comes inside the node should have as it is.
CodePudding user response:
I'm assuming XSLT version 1.0.
It's simply a matter of using the xsl:element
statement to create a new element with a name that's calculated based on the @name
attribute of the Field
.
Using an attribute value template for the @name
attribute of the xsl:element
means the new element's name can be dynamically calculated at runtime.
Within the attribute value template, the XPath function translate()
is used to remove any spaces from the @name
.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- rename Field elements based on their @name attribute -->
<xsl:template match="Field[@name]">
<!-- discard spaces in the name -->
<xsl:element name="{translate(@name, ' ', '')}">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<!-- identity template to copy everything else unchanged -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>