JSON 到 XML 使用 XSLT 的转换
JSON to XML Conversion using XSLT
我有 JSON 从 API 返回,如下所示,我想在其中获取最新日期的数据,例如 XML 中的 2022-01-13。请你指导我
daywisedata": {
"2022-01-11": {
"total_earning": 10,
"total_cost": 0
},
"2022-01-12": {
"total_earning": 5,
"total_cost": 10
},
"2022-01-13": {
"total_earning": 20,
"total_cost": 15
}
}
XML需要像
一样返回
<daywisedata>
<total_earning> 20 </total_earning>
<total_cost> 15 </total_cost>
</daywisedata>
考虑以下示例:
XML(包含一个有效(!)JSON)
<JSON>
{
"daywisedata" :
{
"2022-01-11" :
{
"total_cost" : 0,
"total_earning" : 10
},
"2022-01-12" :
{
"total_cost" : 10,
"total_earning" : 5
},
"2022-01-13" :
{
"total_cost" : 15,
"total_earning" : 20
}
}
}
</JSON>
XSLT 3.0
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:variable name="map" select="parse-json(JSON)?daywisedata?*[last()]" />
<results>
<total_cost>
<xsl:value-of select="$map?total_cost"/>
</total_cost>
<total_earning>
<xsl:value-of select="$map?total_earning"/>
</total_earning>
</results>
</xsl:template>
</xsl:stylesheet>
结果
<?xml version="1.0" encoding="UTF-8"?>
<results>
<total_cost>15</total_cost>
<total_earning>20</total_earning>
</results>
我有 JSON 从 API 返回,如下所示,我想在其中获取最新日期的数据,例如 XML 中的 2022-01-13。请你指导我
daywisedata": {
"2022-01-11": {
"total_earning": 10,
"total_cost": 0
},
"2022-01-12": {
"total_earning": 5,
"total_cost": 10
},
"2022-01-13": {
"total_earning": 20,
"total_cost": 15
}
}
XML需要像
一样返回 <daywisedata>
<total_earning> 20 </total_earning>
<total_cost> 15 </total_cost>
</daywisedata>
考虑以下示例:
XML(包含一个有效(!)JSON)
<JSON>
{
"daywisedata" :
{
"2022-01-11" :
{
"total_cost" : 0,
"total_earning" : 10
},
"2022-01-12" :
{
"total_cost" : 10,
"total_earning" : 5
},
"2022-01-13" :
{
"total_cost" : 15,
"total_earning" : 20
}
}
}
</JSON>
XSLT 3.0
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:variable name="map" select="parse-json(JSON)?daywisedata?*[last()]" />
<results>
<total_cost>
<xsl:value-of select="$map?total_cost"/>
</total_cost>
<total_earning>
<xsl:value-of select="$map?total_earning"/>
</total_earning>
</results>
</xsl:template>
</xsl:stylesheet>
结果
<?xml version="1.0" encoding="UTF-8"?>
<results>
<total_cost>15</total_cost>
<total_earning>20</total_earning>
</results>