Search code examples
jsonxmlxsltwebhooksslack

XML to JSON (Webhooks slack)


I would like to convert an XML to JSON using xslt transformation.The purpose is to POST into my slack channel using Incoming Webhooks.

XML File :

    <?xml version="1.0" encoding="UTF-8" ?>
<Asset version="1.0">
    <Process>
        <Date>2017-01-24 14:47:35</Date>
        <Status>Success</Status
>       <Profile>TEST</Profile>
        <Station>DESKTOP</Station>
        <User>Système</User>
        <Application>APP</Application>
    </Process>
    <Source>
    </Source>
    <Target>
        <Name>Hello.mp4</Name>
    </Target>
</Asset>

I tried this :

   <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output method="txt" omit-xml-declaration="yes" encoding="UTF-8"/>
<xsl:template match="/">
{
"text":"<xsl:value-of select="Asset/Process/Profile"/>",
"text":"<xsl:value-of select="Asset/Process/Date"/>",
"text":"<xsl:value-of select="Asset/Target/Name"/>", 
"text":"<xsl:value-of select="Asset/Process/Status"/>", 
}
</xsl:template>
</xsl:stylesheet>

But i've got this error : 500 - missing_text_or_fallback_or_attachments

Do you have any idea ?

I need to have an JSON like this :

 {     "text": "Date: 2017-01-24 14:47:35\n Status: Success\n Profile: TEST\n Station: DESKTOP\n User: Système\n Application: APP"}

https://api.slack.com/incoming-webhooks#sending_messages


Solution

  • Here is the XSLT which produces the desired JSON String:

    XSLT 2.0

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xsl:output method="text" omit-xml-declaration="yes" encoding="UTF-8"/>
        <xsl:template match="/">
            <xsl:text>{ "text": "</xsl:text>
            <xsl:for-each select="Asset/Process/*">
                <xsl:choose>
                    <xsl:when test="position()=1">
                        <xsl:value-of select="concat(local-name(),': ',.,'\n')"/>
                    </xsl:when>
                    <xsl:when test="position()=last()">
                        <xsl:value-of select="concat(' ',local-name(),': ',.)"/>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="concat(' ',local-name(),': ',.,'\n')"/>
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each>
            <xsl:text>"}</xsl:text>
        </xsl:template>
    </xsl:stylesheet>