xslt 3.0 json-to-xml and xml-to-json conversion

吃可爱长大的小学妹 提交于 2020-01-21 03:49:26

问题


Currently I need to convert json to xml and xml to json vice versa using XSLT 3.0 & Saxon-HE.

Below is my json abc.xml file

<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <data>{
        "cars" : [
        {"doors" : "4","price" : "6L"},
        {"doors" : "5","price" : "13L"}
        ]
        }
    </data>
</root>

Below is xsl file xyz.xsl

<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:template match="data">
    <xsl:copy-of select="json-to-xml(.)"/>
</xsl:template>

Below is output xml

<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
    <array key="cars">
        <map>
            <string key="doors">4</string>
            <string key="price">6L</string>
        </map>
        <map>
            <string key="doors">5</string>
            <string key="price">13L</string>
        </map>
    </array>
</map>

Now My Question is how i can get back the same json from the output.xml? I am trying this using xslt function xml-to-json() but the output format is looking incorrect. Below is the xsl and output m getting.

123.xsl

    <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:template match="data">
        <xsl:copy-of select="xml-to-json(.)"/>
    </xsl:template>


</xsl:stylesheet>

Output JSon

Try this example here https://xsltfiddle.liberty-development.net/3NzcBsQ

In xsl I am selecting wrong template named data. because data template is not in output.xml. I am not sure what should i write here.

<xsl:template match="data">

回答1:


You need to match on /, as in

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">

  <xsl:output method="text"/>

  <xsl:template match="/">
      <xsl:value-of select="xml-to-json(.)"/>
  </xsl:template>

</xsl:stylesheet>

then the result is

{"cars":[{"doors":"4","price":"6L"},{"doors":"5","price":"13L"}]}

With

  <xsl:template match="/">
      <xsl:value-of select="xml-to-json(., map { 'indent' : true() })"/>
  </xsl:template>

you get indentation although Saxon is not doing a nice job there:

  { "cars" : 
    [ 
      { "doors" : "4",
        "price" : "6L" },

      { "doors" : "5",
        "price" : "13L" } ] }

https://xsltfiddle.liberty-development.net/b4GWVd/1



来源:https://stackoverflow.com/questions/48947872/xslt-3-0-json-to-xml-and-xml-to-json-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!