2016-09-29 78 views
1

我使用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解釋爲數組而不是對象。

回答

0

您需要注意的第一件事是,無論何時使用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 
    } 
}) 

希望這會有所幫助。

+0

當我想,我在執行了一個錯誤「異常:使用 (R =(拼合payload.ns0#保留* NS0#預約)。) ^ 對發現 '扁平化' 運營商 類型不匹配:空 required:array。「 我想你在我的代碼中發現了其他錯誤,原帖中的代碼已被重新​​修復,以解決這個問題,但主要的錯誤仍然存​​在。 –

+0

如果您至少可以發佈正確的輸入XML和輸出格式,我可以提供更多幫助。 – AnupamBhusari