代码之家  ›  专栏  ›  技术社区  ›  Xav Sc

XSLT3将json输出设置为无键字符串的数组

  •  0
  • Xav Sc  · 技术社区  · 2 年前

    我是xslt的新手, 我有一个包含这些元素的xml

    <cbl:ShippingAddress>
        <cbl:AddressLine AddressLineNumber="1">
            <cbl:Line>line1</cbl:Line>
        </cbl:AddressLine>
        <cbl:AddressLine AddressLineNumber="2">
            <cbl:Line>line2</cbl:Line>
        </cbl:AddressLine>
    </cbl:ShippingAddress>
    

    使用此代码

    <map key="address">
        <array key="lines">
          <xsl:for-each select="/cbl:ShippingAddress/cbl:AddressLine/cbl:Line">
            <map>
              <string key="line">{.}</string>
            </map>
          </xsl:for-each>
        </array>
    </map>
    

    我得到输出

    "lines": [
        {
          "line": "line1"
        },
        {
          "line": "line2"
        }
    ],
    

    我需要我的输出是这样的,但不知道如何

    "lines": [
        "line1",
        "line2"
    ],
    

    如果我只是改变 <array key="lines"> to <array> 我收到错误消息:

    xml到json:的子元素必须具有key属性

    有没有一种简单的方法可以做到这一点?我浏览了很多例子,都找不到

    1 回复  |  直到 2 年前
        1
  •  0
  •   Martin Honnen    2 年前

    实例

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      version="3.0"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      exclude-result-prefixes="#all"
      xmlns="http://www.w3.org/2005/xpath-functions"
      xmlns:cbl="http://example.com/cbl"
      expand-text="yes">
    
      <xsl:output method="text"/>
    
      <xsl:template match="/" name="xsl:initial-template">
        <xsl:variable name="json-xml">
          <map>
            <array key="lines">
              <xsl:for-each select="cbl:ShippingAddress/cbl:AddressLine/cbl:Line/string()">
                <string>{.}</string>
              </xsl:for-each>
            </array>       
          </map>
        </xsl:variable>
        <xsl:value-of select="xml-to-json($json-xml, map { 'indent' : true() })"/>
      </xsl:template>
    
    </xsl:stylesheet>
    

    Online fiddle example .