我使用Dataweave将有效负载中的XML重新格式化为程序所期望的格式:
有效载荷
<reservation>
<id>1</id>
<begin_time>12:00 PM</begin_time>
<end_time>1:00 PM</begin_time>
<other_field>Misc. Data</other_field>
</reservation>
.
.
.
预期产出。
<reservation>
<id>1</id>
<begin_time>12:00 PM</begin_time>
<schedule>
<begin_time>12:00 PM</begin_time>
<end_time>1:00 PM</end_time>
</schedule>
</reservation>
.
.
.
Dataweave Code
%dw 1.0
%output application/xml
%namespace ns0 http://www.collegenet.com/r25
---
using (r = (flatten payload.ns0#reservations.*ns0#reservation))
Reservation: r groupBy $.ns0#reservation_id pluck {
id : $.ns0#reservation_id ,
StartTime: $.ns0#reservation_start_dt,
Schedule : {
ReservationStartDate : $.ns0#reservation_start_dt,
PreEventDate : $.ns0#pre_event_dt,
EventStartDate : $.ns0#event_start_dt,
PostEventDate : $.ns0#post_event_dt,
ReservationEndDate : $.ns0#reservation_end_dt
}
}
每当我尝试这段代码时,我都会收到错误:
&#34;执行时出现异常: 预订:r map { ^ 无法将a:数组强制转换为:object。&#34;
当我尝试完全相同的代码但转换为JSON而不是XML时,转换工作完美。如果我删除了地图,代码可以工作,但它会加入同一标题下所有预订的所有ID。我不明白为什么Anypoint将xml解释为数组而不是对象。
答案 0 :(得分:0)
首先需要注意的是,无论何时使用map进行迭代,都必须使用$
访问当前元素数据并使用$$
进行索引。这里r.ns0#reservation_id
试图从:array强制转换为:object。尝试将代码更改为
%dw 1.0
%output text/xml
%namespace ns0 http://www.mynamespace.com/ns0
---
using (r = (flatten payload.ns0#reservations.*ns0#reservation))
Reservation: r map {
id : $.ns0#reservation_id,
StartTime: $.ns0#reservation_start_dt,
Schedule : {
ReservationStartDate : $.ns0#reservation_start_dt,
ReservationEndDate : $.ns0#reservation_end_dt
}
}
还观察到输入XML的标签名称与代码中使用的名称不同。为了更具可读性,您可以将lambda与map一起使用
%dw 1.0
%output text/xml
%namespace ns0 http://www.mynamespace.com/ns0
---
using (r = (flatten payload.ns0#reservations.*ns0#reservation))
Reservation: r map ((reservation, reservationIndex) -> {
id : reservation.ns0#reservation_id,
StartTime: reservation.ns0#reservation_start_dt,
Schedule : {
ReservationStartDate : reservation.ns0#reservation_start_dt,
ReservationEndDate : reservation.ns0#reservation_end_dt
}
})
希望这有帮助。