使用 XSLT 2.0 将 xml 标签中存在的 Json 文件解析为 XML 单独标签

问题描述 投票:0回答:1

需要 xslt 2.0 的帮助才能实现以下要求。

  • 输入
<code>"{
  "successful": true,
  "errors": [],
  "elements": [
    {
      "code": "1234567890",
      "channelProcessingTime": 15676456700
    },
    {
      "code": "0987654321",
      "channelProcessingTime": 36509878076
    }
  ]
}"</code>
  • 所需输出:
<code>
    <successful>true</successful>
    <elements>
        <code>1234567890</code>
        <channelProcessingTime>15676456700</channelProcessingTime>
    </elements>
    <elements>
        <code>0987654321</code>
        <channelProcessingTime>36509878076</channelProcessingTime>
    </elements>
</code>

需要 xslt 2.0 的帮助才能实现上述要求。

json xml parsing xslt xslt-2.0
1个回答
0
投票

XSLT 3.0 中,这将是一个微不足道的问题 - 但首先您必须删除 JSON 代码周围的引号才能获得有效的 JSON:

<xsl:stylesheet version="3.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="code">
    <!-- remove surrounding quotes -->
    <xsl:variable name="json" select="replace(., '^&quot;|&quot;$', '')" />
    <code>
        <xsl:apply-templates select="json-to-xml($json)"/>
    </code>
</xsl:template>

<xsl:template match="*[@key]">
    <xsl:element name="{@key}">
        <xsl:apply-templates />
    </xsl:element>
</xsl:template>
    
</xsl:stylesheet>

请注意,如果 JSON 名称不是有效的 XML 元素名称,则此操作可能会失败。

© www.soinside.com 2019 - 2024. All rights reserved.