2016-06-13 39 views
1

使用XSLT转换XML文档时,可以在过程中转换嵌入式JSON(即JSON格式的内容)吗?使用XSLT将嵌入式JSON转换为XML

例如以下内容: -

<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> 

回答

1

解析JSON在XSLT 3.0所以使用撒克逊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> 

使用撒克逊9.7的开源版本(即撒克逊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> 

撒克逊9.7 HE可以用Maven和从http://saxon.sourceforge.net/

+0

Ť但我担心商业提供超出了我的项目范围..我希望获得XSLT 2.0解决方案(Oracle 11gR2数据库内的受支持版本),或者通过导入jar来支持Oracle数据库中的XSLT 3.0的替代方法管他呢。 –

+0

@AlbPuado,我添加了一个与Saxon 9.7开源HE版一起工作的例子,它使用了另一个答案中已经提出的函数'json-to-xml'。至于Oracle和XSLT 2.0,恐怕我不熟悉它和它的扩展功能等特性,如果你正在寻找一个解决方案,可能会比熟悉它的其他人告诉你是否有扩展函数来解析和处理JSON。 –

1

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

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

您可以尝试使其与当前实现在Saxon中运行。