xslt 3.0 json-to-xml 和 xml-to-json 转换 [英] xslt 3.0 json-to-xml and xml-to-json conversion
问题描述
目前我需要使用 XSLT 3.0 & 将 json 转换为 xml,将 xml 转换为 json,反之亦然.萨克森-HE.
Currently I need to convert json to xml and xml to json vice versa using XSLT 3.0 & Saxon-HE.
下面是我的 json abc.xml 文件
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>
下面是xsl文件xyz.xsl
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>
下面是输出的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>
现在我的问题是如何从 output.xml 中取回相同的 json? 我正在尝试使用 xslt 函数 xml-to-json() 但是输出格式看起来不正确.下面是得到的 xsl 和输出 m.
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.
<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>
输出JSon
在这里试试这个例子 https://xsltfiddle.liberty-development.net/3NzcBsQ
在 xsl 中,我选择了错误的模板命名数据.因为数据模板不在 output.xml 中.我不知道我应该在这里写什么.
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">
推荐答案
你需要在/
上进行匹配,如
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>
那么结果就是
{"cars":[{"doors":"4","price":"6L"},{"doors":"5","price":"13L"}]}
与
<xsl:template match="/">
<xsl:value-of select="xml-to-json(., map { 'indent' : true() })"/>
</xsl:template>
尽管 Saxon 在这方面做得不好,但您还是会缩进:
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
这篇关于xslt 3.0 json-to-xml 和 xml-to-json 转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!