微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

数据类型映射:查询键名和返回值

如何解决数据类型映射:查询键名和返回值

我正在尝试使用键名查询 XML 映射(使用 json-to-xml 解析 JSON 文件的结果),以在“for-each”期间获取键值。

我可以使用键索引进行查询,请参阅 test-1。 Test-2 和 Test-3 失败,但我认为我在如何处理对 XML 映射的查询方面存在语法错误

我让 test-1 处于激活状态,并注释掉 test-2/test-3,因为该设置显示了想要的结果。不使用余额,但保留余额只是为了确保它不会传递给结果。

JSON:

<data>
{
"period": {
      "0": {"startDate": "2016-01-01","endDate": "2016-12-31"},"1": {"startDate": "2015-01-01","endDate": "2015-12-31"}
    },"balance": {
      "0": {"instant": "2016-01-01"},"1": {"instant": "2015-01-01"}
    }
}
</data>

XSL:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:transform version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:map="http://www.w3.org/2005/xpath-functions/map"
  xmlns:root="http://www.example.com/1"
  xmlns:periods="http://www.example.com/2"
  expand-text="yes"
>

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

  <xsl:mode on-no-match="shallow-skip"/>

    <!-- Parse JSON to XML -->

    <xsl:template match="data">
        <root:report>
          <xsl:apply-templates select="json-to-xml(.)/*"/>
        </root:report>
    </xsl:template>

    <!-- Process "period" -->

    <xsl:template match="*[@key = 'period']">

      <xsl:for-each select="./*">

            <periods:startDate>

          <!-- Test [1] -->
          <!-- Extract startDate value by index -->
          <xsl:value-of select="./*[1]"/>

          <!-- Test [2] -->
          <!-- Extract startDate value by name -->
          <!-- <xsl:value-of select="startDate"/> -->

          <!-- Test [3] -->
          <!-- Extract startDate by function map:get -->
          <!-- <xsl:variable name="$startDate" select="What to put here?"/>
          <xsl:value-of select="map:get($startDate)"/> -->

        </periods:startDate>

      </xsl:for-each>

    </xsl:template>

</xsl:transform>

想要的结果

<?xml version="1.0" encoding="UTF-8"?>
<root:report xmlns:map="http://www.w3.org/2005/xpath-functions/map"
             xmlns:periods="http://www.example.com/2"
             xmlns:root="http://www.example.com/1">
   <periods:startDate>2016-01-01</periods:startDate>
   <periods:startDate>2015-01-01</periods:startDate>
</root:report>

解决方法

在 for 循环内部,如果您要返回 Map XML 结构:<xsl:sequence select="."/> ,您将看到它如下所示:

<map xmlns="http://www.w3.org/2005/xpath-functions" key="0">
  <string key="startDate">2016-01-01</string>
  <string key="endDate">2016-12-31</string>
</map>

因此,对于您的第二个测试,为了提取 startDate,请通过 @key 属性选择元素:

<!-- Test [2] -->
<!-- Extract startDate value by name -->
<xsl:value-of select="*[@key='startDate']"/>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。