使用XSLT将嵌入式JSON转换为XML

时间:2016-06-13 09:29:07

标签: json xml xslt

使用XSLT转换XML文档时,是否可以在流程中转换嵌入式JSON(即JSON格式的内容)?

例如以下内容: -

<form>
    <data>[{"id":1,"name":"Hello"},{"id":2,"name":"World"}]</data>
</form>

将转换为: -

<form>
    <data>
        <id name="Hello">1</id>
        <id name="World">2</id>
    </data>
</form>

2 个答案:

答案 0 :(得分:1)

应该可以在XSLT 3.0中,因为它有一个json-to-xml function

  

解析以JSON文本形式提供的字符串,返回   以XML文档节点的形式产生。

您可以尝试使用Saxon中的当前实现来运行它。

答案 1 :(得分:1)

XSLT 3.0支持解析JSON,因此使用Saxon 9.7的商业版本可以使用

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="xs math"
    version="3.0">

    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:mode on-no-match="shallow-copy"/>

    <xsl:template match="data">
        <xsl:copy>
            <xsl:apply-templates select="parse-json(.)?*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match=".[. instance of map(xs:string, item())]">
        <id name="{.?name}">
            <xsl:value-of select=".?id"/>
        </id>
    </xsl:template>

</xsl:stylesheet>

使用Saxon 9.7的开源版本(即Saxon 9.7 HE),以下内容将介绍wero使用json-to-xml提出的建议,并说明如何实现该要求:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="xs math fn"
    version="3.0">

    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="data">
        <xsl:copy>
            <xsl:apply-templates select="json-to-xml(.)//fn:map"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="fn:map">
        <id name="{fn:string[@key = 'name']}">
            <xsl:value-of select="fn:number[@key = 'id']"/>
        </id>
    </xsl:template>

</xsl:stylesheet>

Saxon 9.7 HE在Maven和http://saxon.sourceforge.net/

上可用