使用XSLT 2.0将XML转换为JSON

oknrviil  于 2023-05-30  发布在  其他
关注(0)|答案(1)|浏览(210)

我有一个XSLT,可以将XML转换为JSON,并且工作得很好。但是当我试图修改JSON的值类型时,我无法这样做。
下面是我的XSLT文件代码:

<xsl:template match="json:name" mode="json">
    <xsl:text/>"<xsl:value-of select="json:encode-string(.)"/>":<xsl:text/>
</xsl:template>

<xsl:template match="json:value" mode="json">
    <xsl:choose>
        <xsl:when test="node() and not(text())">
            <xsl:apply-templates mode="json"/>
        </xsl:when>
        <xsl:when test="text()">
            <xsl:choose>
                                    <xsl:when test="normalize-space(.) ne . or not((string(.) castable as xs:integer and not(starts-with(string(.),'+') or starts-with(string(.),'-')) and not(starts-with(string(.),'0') and not(. = '0'))) or (string(.) castable as xs:decimal and not(starts-with(string(.),'+')) and not(starts-with(.,'-.')) and not(starts-with(.,'.')) and not(starts-with(.,'-0') and not(starts-with(.,'-0.'))) and not(ends-with(.,'.')) and not(starts-with(.,'0') and not(starts-with(.,'0.'))))) and not(. = 'false') and not(. = 'true') and not(. = 'null')">
                                        <xsl:text/>"<xsl:value-of select="json:encode-string(.)"/>"<xsl:text/>
                                    </xsl:when>
                <xsl:otherwise>
                    <xsl:text/><xsl:value-of select="."/><xsl:text/>
                </xsl:otherwise>

            </xsl:choose>
        </xsl:when>
        <xsl:otherwise>
            <xsl:text>null</xsl:text>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

我想添加一个条件,如果xml元素名为id并且非null,则将其转换为字符串。
我试过下面的东西,但它没有工作。

<xsl:template match="id">
    <xsl:choose>
        <xsl:when test="id">
            <xsl:text/>"<xsl:value-of select="json:encode-string(.)"/>"<xsl:text/>
        </xsl:when>
    </xsl:choose>
</xsl:template>

如何将这些元素作为键值对迭代,以便在名称匹配时向value添加条件逻辑?
编辑:
添加了示例XML:

<?xml version="1.0" encoding="UTF-8"?>
 <ns0:TestMe xmlns:ns0="urn:hero:wakanda:Cle:Something">
   <root>
     <id>123</id>
     <field2>345</field2>
     <fee>
        <totalFee>123</totalFee>
    </fee>
    </root>
    </ns0:TestMe>

使用此XML到JSON转换器文件:https://github.com/bramstein/xsltjson/blob/master/conf/xml-to-json.xsl

uqjltbpv

uqjltbpv1#

在从您的问题编辑链接到的样式表的上下文中,我认为您需要类似于

<xsl:template match="json:member[json:name = 'id']/json:value" mode="json">
    <xsl:text>"</xsl:text>
    <xsl:value-of select="json:encode-string(.)"/>
    <xsl:text>"</xsl:text>
  </xsl:template>

以得到例如"id":"123"而不是例如"id":123

相关问题