3

目前我需要使用 XSLT 3.0 和 Saxon-HE 将 json 转换为 xml 和 xml 到 json,反之亦然。

下面是我的 json abc.xml 文件

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

下面是 xsl 文件 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。

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>

输出 JSON

在此处输入图像描述

在这里试试这个例子https://xsltfiddle.liberty-development.net/3NzcBsQ

在 xsl 中,我选择了错误的名为 data 的模板。因为数据模板不在 output.xml 中。我不确定我应该在这里写什么。

<xsl:template match="data">
4

1 回答 1

9

您需要匹配 on /,如

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

尽管撒克逊人在那里做得不好,但你会得到缩进:

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

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

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

于 2018-02-23T13:25:44.440 回答