如何解决使用XSLT将XML转换为JSON并将方括号[]添加到JSON
在使用XSLT进行转换之后,Am试图将方括号括起来/添加到Json。我希望Json采用列表/数组形式。
下面是我的XML文件。
<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
<string key="foedselsdato">2019-04-22</string>
<string key="individId">01387</string>
<map key="varslinger"/>
</map>
这是我下面的XSL文件。
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="3.0">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:value-of select="xml-to-json(.,map { 'indent' : true() })"/>
</xsl:template>
</xsl:stylesheet>
使用https://xsltfiddle.liberty-development.net/b4GWVd进行转换,我得到了:
{ "foedselsdato" : "2019-04-22","individId" : "01387","varslinger" :
{ } }
但是我想将其转换如下:
[{ "foedselsdato" : "2019-04-22","varslinger" :
{ } }]
解决方法
如果要在XPath 3.1和XSLT 3中使用JSON的XDM表示形式,可以使用
<xsl:output method="json" indent="yes"/>
<xsl:template match="/">
<xsl:sequence select="array { xml-to-json(.) => parse-json() }"/>
</xsl:template>
将先前的JSON包装到一个数组中:https://xsltfiddle.liberty-development.net/b4GWVd/81
,以下代码有效。
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="3.0">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:text>[</xsl:text>
<xsl:value-of select="xml-to-json(.,map { 'indent' : true() })"/>
<xsl:text>]</xsl:text>
</xsl:template>
</xsl:stylesheet>
或
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="3.0">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:text>[</xsl:text>
<xsl:value-of select="concat('[',xml-to-json(.,map { 'indent' : true() }))"/>
<xsl:text>]</xsl:text>
</xsl:template>
</xsl:stylesheet>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。