json - 数据类型映射:从当前元素导航到父元素名称
问题描述
对于所有时期元素,我需要使用通用 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>
解决方案
您可以使用/*: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']
。
推荐阅读
- ember.js - Ember JS:在控制台中访问 peekAll 长度
- apache-spark - Spark并行范围与使用多线程提交拆分范围之间的区别?
- flutter - 如何在调试模式下测试inApp购买颤振
- python - 在 DynamoDB 中,给定一个表,我可以通过编程方式找到主键(哈希键和排序键)
- html - 边距不会在两个子元素之间创建空间,但填充可以
- ios - 使用 forcereact 创建的 Salesforce React Native 示例应用程序无法在 iOS 中构建,但在 Android 中无法构建
- c# - Xamarin UITest,可以在测试中使用 AppResource 功能吗?
- reactjs - React - 嵌套路由 - 获取当前 URL 的深度
- c# - 哪个对象用于在内存中对有间隙的查找数据进行排序
- string - 错误“在抛出 'std::length_error' what(): basic_string::_S_create 的实例后调用终止”