使用XSLT转换不含XML标签的JSON为XML的方案咨询
XSLT实现纯JSON到指定XML结构转换方案
场景背景
需要通过XSLT完成JSON到XML的格式转换,待转换JSON不包含预置XML标签,无法适配常规要求JSON内嵌XML标识的转换逻辑。
参考输入输出
待转换JSON示例
{ "SARIETransferRq": { "SARIETransferRqHeader": { "CorporateID": "ABCD0001", "CorpReferenceNumber": "4716936" }, "SARIETransferRqBody": { "AccountNumber": "02020202020", "DebitCurrency": "SAR", "Instructions2": "luaba", "Instructions3": "fadjiugu", "Instructions4": "rifdij", "Description": "sample description for service fee", "AMLPurposeCode": "BB" } }, "Signature": { "SignatureValue": "sample" } }
目标输出XML格式
<?xml version="1.0" encoding="UTF-8" ?> <root> <SARIETransferRq> <SARIETransferRqHeader> <CorporateID>ABCD0001</CorporateID> <CorpReferenceNumber>4716936</CorpReferenceNumber> </SARIETransferRqHeader> <SARIETransferRqBody> <AccountNumber>02020202020</AccountNumber> <DebitCurrency>SAR</DebitCurrency> <Instructions2>luaba</Instructions2> <Instructions3>fadjiugu</Instructions3> <Instructions4>rifdij</Instructions4> <Description>sample description for service fee</Description> <AMLPurposeCode>BB</AMLPurposeCode> </SARIETransferRqBody> </SARIETransferRq> <Signature> <SignatureValue>sample</SignatureValue> </Signature> </root>
实现方法
使用支持XSLT 3.0标准的处理器(如Saxon-HE 9.8及以上版本、SaxonJS)即可实现,不需要在JSON中预置任何XML标签,直接利用XSLT 3.0原生的JSON解析能力,通过递归模板完成结构映射即可,完整代码如下:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fn="http://www.w3.org/2005/xpath-functions" exclude-result-prefixes="fn"> <xsl:output method="xml" encoding="UTF-8" indent="yes"/> <!-- 转换入口 --> <xsl:template match="/"> <root> <!-- 若JSON通过输入流传入而非外部文件,替换unparsed-text部分为对应JSON内容读取逻辑 --> <xsl:apply-templates select="json-to-xml(unparsed-text('your-json-file-path.json'))/*"/> </root> </xsl:template> <!-- 递归处理JSON对象,将JSON键直接映射为XML元素名 --> <xsl:template match="fn:map"> <xsl:for-each select="fn:*"> <xsl:element name="{@key}"> <xsl:apply-templates select="."/> </xsl:element> </xsl:for-each> </xsl:template> <!-- 处理JSON字符串值,直接输出文本内容 --> <xsl:template match="fn:string"> <xsl:value-of select="."/> </xsl:template> <!-- 若业务JSON包含数组,放开此段逻辑即可自动遍历数组成员,当前示例无数组可删除 --> <!-- <xsl:template match="fn:array"> <xsl:apply-templates select="fn:*"/> </xsl:template> --> </xsl:stylesheet>
注意事项
- 若使用不支持XSLT 3.0的老旧处理器,本身没有内置JSON解析能力,不建议手写字符串解析逻辑处理JSON,容错率极低,优先升级处理器版本,或在XSLT调用前通过外层代码完成JSON预解析再传入。
- 上述代码直接按照JSON键名映射XML标签,和示例的输入输出完全匹配,如果后续JSON结构新增键值对,不需要修改XSLT代码即可自动生成对应XML节点。
内容的提问来源于stack exchange,提问作者Varaprasad Bolisetty
相关产品推荐
相关产品推荐

