2016-06-13 78 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中運行。