In WSO2 ESB, we can use the Script Mediator manipulate a XML payload. Here I have used JavaScript/E4X for accessing/manipulating the elements.
Example XML payload;
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<calories>900</calories>
</food>
</breakfast_menu>
Lets assume we want to remove the last food element (Berry-Berry Belgian Waffles); In this scenario, breakfast_menu is the root element and the set of children elements will be food.
The length of the child elements (food) can be obtained as follows;
Example XML payload;
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<calories>900</calories>
</food>
</breakfast_menu>
Lets assume we want to remove the last food element (Berry-Berry Belgian Waffles); In this scenario, breakfast_menu is the root element and the set of children elements will be food.
The length of the child elements (food) can be obtained as follows;
var payload = mc.getPayloadXML(); var length = payload.food.length();
Then delete the last element as follows; Here the index of the last element would be length-1
delete payload.cuidInfo[length-1];Complete Script Mediator configuration would be as follows;<script language="js"> var payload = mc.getPayloadXML(); var length = payload.food.length(); delete payload.food[length-1]; mc.setPayloadXML(payload); </script>The output of the script mediator would be as follows;<breakfast_menu> <food> <name>Belgian Waffles</name> <price>$5.95</price> <calories>650</calories> </food> <food> <name>Strawberry Belgian Waffles</name> <price>$7.95</price> <calories>900</calories> </food> </breakfast_menu>
NOTE:
<script language="js">var log = mc.getServiceLog(); var message = mc.getPayloadXML(); log.info(":: Message ::"+message); log.info(":: Message Header ::"+message..*::Header.*::To); delete message..*::Header..*::To; mc.setPayloadXML(message);</script><script language="js">var log = mc.getServiceLog(); var message = mc.getPayloadXML(); log.info(":: Message ::"+message); log.info(":: Message Header ::"+message..*::Header.*::To[0]); delete message..*::Header..*::To[0]; mc.setPayloadXML(message);</script>
No comments:
Post a Comment