Chetan Potdar Chetan Potdar - 4 months ago 7x
JSON Question

Unable to fetch attributes from XML using XSLT

I am trying to extract the values of attributes from XML to JSON using XSLT.


<test attr1="123" attr2="abc"/>


"attr1":"<xsl:value-of select="root1/root2/test/[@attr1"]/>"
"attr2":"<xsl:value-of select="root1/root2/test/[@attr2"]/>"

I tried many solutions but none of them are working. Headers and footer for XSLT is already taken care.


When writing xsl you should adopt best practices and use templates for repeatative content. So in your example you should use a template to transform the attributes like so..

<xsl:stylesheet xmlns:xsl="" version="2.0">
  <xsl:template match="/">
    <xsl:apply-templates select="root1/root2/test/@*"/>
  <xsl:template match="@*">
    <xsl:if test="position()>1"><xsl:text>,</xsl:text></xsl:if>
    <xsl:value-of select="name()"/>
    <xsl:value-of select="."/>

In the xsl above I'm using a template that will a single attribute into a json name/value pair and the apply-templates is used to select all attributes from the root/root2.test node.