【问题标题】:Using XSLT to transform XML to JSON and add Square bracket [] to the JSON使用 XSLT 将 XML 转换为 JSON 并将方括号 [] 添加到 JSON
【发布时间】:2021-01-05 04:23:43
【问题描述】:

在使用 XSLT 进行转换后,我试图将方括号括起来/添加到 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",
    "individId" : "01387",
    "varslinger" : 
    {  } }]

【问题讨论】:

  • concat 怎么样?
  • 我该怎么做,当我使用表达式
  • 反其道而行之。将 xml-to-json 放入 concat 中。
  • 感谢@ceving 也可以。 w3.org/1999/XSL/Transform" version="3.0">

标签: json xml xslt xslt-3.0


【解决方案1】:

以下代码有效。

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

【讨论】:

    【解决方案2】:

    如果您想在 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

    【讨论】:

      猜你喜欢
      • 2021-07-21
      • 2020-10-28
      • 2020-01-26
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 2019-12-28
      相关资源
      最近更新 更多