Scala Play更新XML请求

Scala Play更新XML请求,xml,scala,playframework,Xml,Scala,Playframework,我正在将一个XML发布到我的Play应用程序中,我希望我的控制器操作查找特定字段,更新字段值,并将其发送回 XML示例: <name>shrek</name> <type>ogre</type> <category>dank</category> 我已经看了播放文档,但它非常有限,如何返回带有更新字段的XML,例如将shrek更改为kek 是的,我们在中没有找到太多关于XML解析和更新的信息 但我们可以通过将XML节点视为

我正在将一个XML发布到我的Play应用程序中,我希望我的控制器操作查找特定字段,更新字段值,并将其发送回

XML示例:

<name>shrek</name>
<type>ogre</type>
<category>dank</category>

我已经看了播放文档,但它非常有限,如何返回带有更新字段的XML,例如将
shrek
更改为
kek

是的,我们在中没有找到太多关于
XML
解析和更新的信息

但我们可以通过将
XML节点
视为
Scala类

下面是一个在您的条件下工作的示例

为XML对象创建scala模型

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

  def toXML = { //converts to XML
    <xml>
      <name>{name}</name>
      <type>{itemType}</type>
      <category>{category}</category>
    </xml>
  }

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

  //some other utilities of your choice

}
您的控制器:

  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")
    Ok(updatedXML)
    //Output: YourName ogre dank
  }
同样,我们可以为每个
XML请求创建
scala类
,并编写自己的实用程序函数进行操作

如果我在
play framework
中找到任何库或实用程序来执行此操作,我将在此更新

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)
  }

}
  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")
    Ok(updatedXML)
    //Output: YourName ogre dank
  }