如何在XSLT中解析XML内嵌JSON结构的指定字段值
XSLT 3.0实现从指定JSON结构提取字段生成XML
核心实现逻辑
- 用
json-to-xml()将XML中嵌套的JSON字符串转换为XML节点集,便于通过XPath选择目标字段 - 定位
InputParameters里key值为CanonicalMessage的条目,获取对应的JSON内容 - 从转换后的XML节点中提取
OperationName、Payload/Title、Payload/ID三个字段值 - 按照指定结构组装输出XML
示例输入XML
<Root> <InputParameters> <entry> <key>CanonicalMessage</key> <value>{"OperationName":"CreateOrder","Payload":{"Title":"CustomerOrder","ID":"ORD-12345"}}</value> </entry> <entry> <key>OtherParam</key> <value>{"SomeKey":"SomeValue"}</value> </entry> </InputParameters> </Root>
完整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:apply-templates select="Root/InputParameters/entry[key='CanonicalMessage']"/> </xsl:template> <xsl:template match="entry[key='CanonicalMessage']"> <!-- 转换JSON为XML结构 --> <xsl:variable name="json-xml" select="json-to-xml(value)"/> <!-- 提取目标字段值 --> <xsl:variable name="op-name" select="$json-xml/*[@key='OperationName']/text()"/> <xsl:variable name="doc-title" select="$json-xml/*[@key='Payload']/*[@key='Title']/text()"/> <xsl:variable name="doc-id" select="$json-xml/*[@key='Payload']/*[@key='ID']/text()"/> <!-- 生成预期结构的XML --> <ProcessedMessage> <Action><xsl:value-of select="$op-name"/></Action> <Content> <DocumentTitle><xsl:value-of select="$doc-title"/></DocumentTitle> <DocumentID><xsl:value-of select="$doc-id"/></DocumentID> </Content> </ProcessedMessage> </xsl:template> <!-- 忽略非CanonicalMessage的参数条目 --> <xsl:template match="entry[key!='CanonicalMessage']"/> </xsl:stylesheet>
预期输出XML
<ProcessedMessage> <Action>CreateOrder</Action> <Content> <DocumentTitle>CustomerOrder</DocumentTitle> <DocumentID>ORD-12345</DocumentID> </Content> </ProcessedMessage>
关键说明
json-to-xml()是XSLT 3.0核心函数,会将JSON对象转为带key属性的XML节点,比如JSON的{"OperationName":"xxx"}会被转为<map><string key="OperationName">xxx</string></map>- 利用XPath路径可以精准定位嵌套的Payload字段,无需复杂的字符串处理
- 通过模板匹配过滤无关条目,确保输出仅包含目标内容
内容的提问来源于stack exchange,提问作者Sateesh
相关产品推荐
相关产品推荐

