首页 > 解决方案 > 数据类型映射:从当前元素导航到父元素名称

问题描述

对于所有时期元素,我需要使用通用 url,它以并行级别存储在相同的 JSON 数据/XML 映射中。因此,我尝试使用当前节点作为起点导航到元素“url”。我可以使用索引号而不是键名来做到这一点。

我激活了 test-3 但注释掉了其他测试,因为 test-3 给出了想要的结果。

问题:是否可以使用键名而不是索引号来查询 XML 映射?

如果无法在地图中使用相对导航,那么我可以通过其他方式查询元素“url”。

JSON:

<data>
{

"url": "http:www.example-10.com",

"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>

              <xsl:attribute name="url">

                <!-- Test [1] get's all values from current node -->
                <!-- <xsl:value-of select="."/> -->

                <!-- Test [2] get's first value from current node  -->
                <!-- <xsl:value-of select="./*[1]"/> -->

                <!-- Test [3] Attempt to find parent element "url" with index  -->
                <xsl:value-of select="../../*[1]"/>

                <!-- Test [4] Attempt to find parent element "url" with name  -->
                <!-- <xsl:value-of select="../../url"/> -->

              </xsl:attribute>

          <xsl:value-of select="./*[1]"/>


        </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 url="http:www.example-10.com">2016-01-01</periods:startDate>
   <periods:startDate url="http:www.example-10.com">2015-01-01</periods:startDate>
</root:report>

标签: jsonxmlxsltxslt-3.0

解决方案


您可以使用/*:map/*:string[@key = 'url']或声明fn命名空间(使用 eg xmlns:fn="http://www.w3.org/2005/xpath-functions")并使用它而不是使用 eg 的通配符/fn:map/fn:string[@key = 'url']

或向上,例如../../fn:string[@key = 'url']


推荐阅读