简体   繁体   English

如何使用 XSLT 将单个子 xml 元素转换为 Json 数组

[英]How to convert single child xml element to Json Array using XSLT

I am using a generic xslt( http://www.bizcoder.com/convert-xml-to-json-using-xslt ) to convert xml into json which works just fine when there are multiple array elements in request and now I want to convert a particular xml element even tough it has single child element.For example:我正在使用通用 xslt( http://www.bizcoder.com/convert-xml-to-json-using-xslt )将 xml 转换成 Z466DEEC76ECDF5FCA6D38571F6324D要转换特定的 xml 元素,即使它有单个子元素也很难。例如:

Sample XML样品 XML

<messages>
<message>
<to>Karim</to>
<from>Tom</from>
<heading>Reminder</heading>
<body>Please check your email !</body>
</message>
</messages>
<?xml version="1.0" encoding="UTF-8"?> 
<Response>
<Info id="10485824">
<Data tipus="11" megnevezes="APEH hátralék (rendezetlen)">
<Value num="1" subtype="xbool">false</Value>
</Data> 
</Info>
</Response>

Sample JSON:样品 JSON:


    {
        "messages": {
            "message": [{
                "to": "Karim",
                "from": "Tom",
                "heading": "Reminder",
                "body": "Please check your email !"
            }]
        }
    }

Is there any we can add in the xslt to filter only this element to return as json array always?我们可以在 xslt 中添加任何内容以仅过滤此元素以始终返回为 json 数组吗?

Change the condition to create the array to将创建数组的条件更改为

<!-- Object Properties -->
<xsl:template name="Properties">
    <xsl:variable name="childName" select="name(*[1])"/>
    <xsl:choose>
        <xsl:when test="not(*|@*)">"<xsl:value-of select="."/>"</xsl:when>
        <xsl:when test="$childName = 'message' or count(*[name()=$childName]) > 1">{ "<xsl:value-of select="$childName"/>" :[<xsl:apply-templates select="*" mode="ArrayElement"/>] }</xsl:when>
        <xsl:otherwise>{
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates select="*"/>
}</xsl:otherwise>
    </xsl:choose>
    <xsl:if test="following-sibling::*">,</xsl:if>
</xsl:template>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM