如何在XSLT 4.0中遍历JSON数组生成目标JSON结构
XSLT 4.0处理JSON生成预期结构解决方案
问题背景
原XSLT 4.0处理JSON逻辑在结构变更后出现SERE0023序列化错误,添加array解决错误但输出不符合预期:每个publisher下的所有book Name被打包成一个数组对象。需要调整为每个book单独生成包含resourceType和identifier的对象,尝试用for-each时触发XPST0003错误(XPath中不允许XQuery节点构造表达式)。
相关代码
输入JSON (sample.json)
{ "publishers": [ { "sellers": { "books": [ { "test": { "count": 1 }, "Name": "C", "Type": "String" }, { "test": { "count": 2 }, "Name": "C++", "Type": "String" } ], "Author": "Michel" } }, { "sellers": { "books": [ { "test": { "count": 3 }, "Name": "Python", "Type": "String" }, { "test": { "count": 4 }, "Name": "Java", "Type": "String" } ], "Author": "Robert" } } ] }
原XSLT (sample.xslt)
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="4.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="#all"> <xsl:output method="json" indent="yes"/> <xsl:template match="." name="xsl:initial-template"> <xsl:sequence select="array { ?publishers?* ! map { 'resourceType' : 'Asset', 'identifier' : map {'name' : array{?sellers?books?*?Name}} } }"/> </xsl:template> </xsl:stylesheet>
当前错误输出 (wrongOutput.json)
[ { "resourceType": "Asset", "identifier": { "name": [ "C", "C++" ] } }, { "resourceType": "Asset", "identifier": { "name": [ "Python", "Java" ] } } ]
期望输出 (result.json)
[ { "resourceType": "Asset", "identifier": { "name":"C" } }, { "resourceType": "Asset", "identifier": { "name":"C++" } }, { "resourceType": "Asset", "identifier": { "name":"Python" } }, { "resourceType": "Asset", "identifier": { "name":"Java" } } ]
解决方案
修改后的XSLT代码
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="4.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="#all"> <xsl:output method="json" indent="yes"/> <xsl:template match="." name="xsl:initial-template"> <xsl:sequence select="array { ?publishers?* ! ?sellers?books?* ! map { 'resourceType' : 'Asset', 'identifier' : map {'name' : ?Name} } }"/> </xsl:template> </xsl:stylesheet>
代码说明
- 层级遍历调整:使用
?publishers?* ! ?sellers?books?*展开所有层级到单个book对象,替代原有的按publisher分组逻辑。 - 避免XQuery构造:用XPath的序列展开运算符
!替代XQuery的for-each,规避XPST0003错误。 - 单个Name映射:对每本book直接取
?Name作为identifier的name值,不再打包成数组。
验证结果
执行修改后的XSLT,输出将完全匹配期望的result.json结构,每个book对应独立的Asset对象。
内容的提问来源于stack exchange,提问作者Sujit Kumar
相关产品推荐
相关产品推荐

