我正在使用 XSLT 处理各种 XML 文件。在一个 XML 中,我发现了一个包装好的 JSON 列表:
<list><![CDATA[[
{
"title": "Title 1",
"value": "Value 1",
"order": 1
},
{
"title": "Title 2",
"value": "Value 2",
"order": 2
}
]]]>
</list>
我的问题是我需要遍历列表。例如:
<xsl:variable name="listVar">
<!-- do something with list -->
</xsl:variable>
<xsl:for-each select="$listVar">
<!-- do something with objects in list e.g. -->
<xsl:value-of select="title"/>
<xsl:value-of select="value"/>
</xsl:for-each>
如何用 XSLT 做到这一点?我使用 XSLT 3.0 和 Saxon 引擎,版本 9.8 HE。
考虑的解决方案:
一、使用parse-json
功能:
但是由于 XPathException,我无法遍历结果:“子轴的上下文项的必需项类型是节点();提供的值(。)具有项类型数组(函数(*))”或“地图不能雾化”。我发现有些功能可能我应该考虑在内,例如 map:get、map:entry,但到目前为止我还没有在我的案例中使用它们。
2. 上述变换前的附加变换:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="3.0">
<xsl:output method="xml" encoding="UTF-8" indent="no"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="list">
<list>
<xsl:copy-of select="json-to-xml(.)"/>
</list>
</xsl:template>
</xsl:stylesheet>
进而:
<xsl:variable name="listVar" select="list/array/map"/>
但它不起作用 - 可能是由于添加了命名空间
<list>
<array xmlns="http://www.w3.org/2005/xpath-functions">
<map>
...