DarthBinks911 DarthBinks911 - 1 year ago 74
Scala Question

Scala Play updating an XML request

I'm posting an XML to my Play application, and I want my controller action to look for a specific field, update the field value, and send it back.

Example XML:


My controller action that just returns the same XML I'm posting:

def updateShrekXML() = Action(parse.xml) { request =>

I've looked at the Play documentation but it is very limited, how can I return the XML with an updated field, for example changing

Answer Source

Yes we didn't find much about XML parsing and updating in Docs.

But We can achieve this by considering XML Node as Scala Class

Here is a working example which works in your condition

create a scala model for your XML object

class SomeXML(var name: String, var itemType: String, var category: String){

  def toXML = { //converts to XML

  //we can also use setters / getters without writing XML node everytime. Just calling .toXML gives the node
  def updateName(newName: String) ={ //updates name

  //some other utilities of your choice


Same class object to deserialize XML

object SomeXML {

  def fromXML(xmlNode: scala.xml.Node) = { //converts XML to Scala Object
    val name = (xmlNode \ "name").text
    val itemType = (xmlNode \ "type").text
    val category = (xmlNode \ "category").text
    new SomeXML(name, itemType, category)


Your Controller:

  def updateXML() = Action(parse.xml) { request =>
    val originalXML = SomeXML.fromXML(request.body.head) //(.head) reads XML node from Node sequence
    val updatedXML = originalXML.updateName("YourName")
    //Output: YourName ogre dank

In the same we can create scala class for every XML request and write your own utility functions to manipulate.

I'll update here if I found any Libraries or Utilities to do this in play framework.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download