Dataweave XML-XML转换“无法强制将a:数组转换为:字符串”。
问题描述:
我使用Dataweave重新格式化从有效载荷将XML格式的节目期待:Dataweave XML-XML转换“无法强制将a:数组转换为:字符串”。
有效载荷
<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代码
%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
}
}
每当我尝试这个代码,我得到一个错误:
"Exception while executing: Reservation: r map { ^ Cannot coerce a :array to a :object."
当我尝试完全相同的代码,但转换成JSON,而不是XML,改造工程完美。如果我删除了该地图的代码,但它会加入同一标题下所有预订的所有ID。我不明白为什么Anypoint将xml解释为数组而不是对象。
答
您需要注意的第一件事是,无论何时使用map进行迭代,必须使用$
和$$
访问当前元素数据。这里r.ns0#reservation_id
试图强制:来自:数组的对象。尝试将代码更改为
%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具有与代码中使用的名称不同的标记名称。为更多的可读性,你可以使用拉姆达与地图
%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
}
})
希望这会有所帮助。
当我想,我在执行了一个错误“异常:使用 (R =(拼合payload.ns0#保留* NS0#预约)。) ^ 对发现 '扁平化' 运营商 类型不匹配:空 required:array。“ 我想你在我的代码中发现了其他错误,原帖中的代码已被重新修复,以解决这个问题,但主要的错误仍然存在。 –
如果您至少可以发布正确的输入XML和输出格式,我可以提供更多帮助。 – AnupamBhusari