首页 > 解决方案 > 如何在 XSLT 中将 XML 转换为 Json?

问题描述

如何在xslt中将xml转换为json

输入xml:

<root>
    <citiID>RR1</citiID>
    <bib>ertyokf (5208). Free <Emphasis Type="Italic">of detachment</Emphasis>, aedrtg. dcdcdr<b>49</b> any text</bib>
</root>

预期的Json:

  "root": [
    {
        "citeid": "RR1",
        "bib": "ertyokf (5208). Free <Emphasis Type=\"Italic\">of detachment</Emphasis>, aedrtg. dcdcdr<b>49</b> any text."
    },
    ]

标签: jsonxmlxsltxslt-2.0xslt-3.0

解决方案


您可以使用两种方法,一种是将所需的 JSON 直接表示为 XDM 3.1 映射和数组:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    exclude-result-prefixes="#all"
    version="3.0">


  <xsl:output method="json" indent="yes"/>

  <xsl:template match="/*">
    <xsl:sequence
      select="map {
        local-name() : array {
          map:merge(* ! map {
            lower-case(local-name()) : serialize(node())
          })
        }
      }"/>
  </xsl:template>
  
</xsl:stylesheet>

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

第二个是将输入的 XML 转换为xml-to-json函数使用的 JSON 的 XML 表示。


推荐阅读