OIC中XSLT嵌套API响应转单数组并按条件映射TerminationDate
问题描述
在Oracle Integration Cloud(OIC)中使用XSLT处理嵌套结构的API响应,需完成两个核心需求:
- 将嵌套结构转换为单数组进行处理
- 按规则映射
TerminationDate字段(该字段可为空):- 若数组中任意一条记录的
TerminationDate在当前日期的15天范围内,将该日期映射到目标字段 - 若所有
TerminationDate均不在15天范围内,或全为空,则返回null
- 若数组中任意一条记录的
源数据示例
<SourceResponse> <NestedData> <Records> <Record> <ID>1</ID> <TerminationDate>2024-05-20</TerminationDate> </Record> <Record> <ID>2</ID> <TerminationDate></TerminationDate> </Record> <Record> <ID>3</ID> <TerminationDate>2024-06-10</TerminationDate> </Record> </Records> </NestedData> </SourceResponse>
期望输出示例
假设当前日期为2024-05-10,第一条记录的日期符合15天范围要求,输出如下:
<TargetResponse> <CriticalTerminationDate>2024-05-20</CriticalTerminationDate> </TargetResponse>
若所有日期均不在范围内或为空,输出如下:
<TargetResponse> <CriticalTerminationDate xsi:nil="true"/> </TargetResponse>
解决方案XSLT代码
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <!-- 定义当前日期及15天后的日期变量 --> <xsl:variable name="currentDate" select="current-date()"/> <xsl:variable name="15DaysLater" select="$currentDate + xs:dayTimeDuration('P15D')"/> <xsl:template match="/"> <TargetResponse> <CriticalTerminationDate> <!-- 筛选非空且在15天范围内的TerminationDate --> <xsl:variable name="matchingDates" select=" /SourceResponse/NestedData/Records/Record/TerminationDate[ string(.) != '' and xs:date(.) ge $currentDate and xs:date(.) le $15DaysLater ]"/> <!-- 根据筛选结果输出对应值或null --> <xsl:choose> <xsl:when test="$matchingDates"> <xsl:value-of select="$matchingDates[1]"/> </xsl:when> <xsl:otherwise> <xsl:attribute name="xsi:nil">true</xsl:attribute> </xsl:otherwise> </xsl:choose> </CriticalTerminationDate> </TargetResponse> </xsl:template> </xsl:stylesheet>
代码逻辑说明
- 日期计算:用
current-date()获取标准格式的当前日期,通过xs:dayTimeDuration('P15D')计算15天后的日期,确保日期比较的准确性 - 筛选逻辑:先过滤空值的
TerminationDate,再检查日期是否处于当前日期 ≤ 目标日期 ≤ 当前日期+15天的区间内 - 结果处理:若存在符合条件的日期,取第一条返回;若无符合条件的记录,则添加
xsi:nil="true"属性表示null - 嵌套结构处理:通过
/SourceResponse/NestedData/Records/Record直接遍历所有嵌套记录,自动实现嵌套结构到单数组的逻辑转换
注意事项
- 确保OIC使用的XSLT版本为2.0(OIC默认支持该版本)
TerminationDate必须为YYYY-MM-DD的标准日期格式,若格式不符需先添加日期格式化处理逻辑- 若需要匹配过去15天到未来15天的范围,可将日期比较条件调整为:
xs:date(.) ge $currentDate - xs:dayTimeDuration('P15D') and xs:date(.) le $15DaysLater
内容的提问来源于stack exchange,提问作者Arun M
相关产品推荐
相关产品推荐

