简体   繁体   中英

Scala Xml auto transient when value is null

I know to generate xml with pojo I can do something like this,

    class Person(name : String, age : Int){
        def toXml() = <person><name>{ name }</name><age>{ age }</age></person>;
    }

The problem is that if name = null, the I would have

    <person><name></name><age>8</age></person>

when really, I want the node to be transient when the value is null

    <person><age>8</age></person>

Is there a clean way to accomplish this? thanks.

The following code works for me.

<person>{if(name != "")  <name>{name}</name>}</person>

Cheers

If name can be null, another (more functional?) approach is to use Option:

class Person(name : Option[String], age : Int){
  def toXml() = <person>{name map {x=> <name>{x}</name>} getOrElse(<name/>)} <age>{ age }</age></person>;
}

I'm pretty sure it can be made less verbose, but the advantage is that you're specifying that name is optional and then the type checker will force to deal with that. With a plain String you need to remember the null check by yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM