xslt 3.0 json-to-xml и xml-json

В настоящее время мне нужно конвертировать json в xml и xml в json наоборот, используя XSLT 3.0 и Saxon-HE.

Ниже мой файл 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>

Теперь мой вопрос, как я могу получить тот же JSON из файла output.xml? Я пытаюсь это с помощью функции 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">

1 ответ

Решение

Вы должны соответствовать на /, как в

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

Другие вопросы по тегам