加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何根据选项添加XML属性?

发布时间:2020-12-16 07:52:36 所属栏目:百科 来源:网络整理
导读:我已经编写了一个makeMsg函数,但是我不喜欢它 – 它似乎根本就不是基于Option.isDefined来区分 Scala-ish.你能做得更好吗 scala def makeMsg(t: Option[String]) = | if (t.isDefined) msg text={t.get} / else msg /makeMsg: (t: Option[String])scala.xml.
我已经编写了一个makeMsg函数,但是我不喜欢它 – 它似乎根本就不是基于Option.isDefined来区分 Scala-ish.你能做得更好吗
scala> def makeMsg(t: Option[String]) = 
     | if (t.isDefined) <msg text={t.get} /> else <msg />
makeMsg: (t: Option[String])scala.xml.Elem

scala> makeMsg(Some("hello"))
res0: scala.xml.Elem = <msg text="hello"></msg>

scala> makeMsg(None)
res1: scala.xml.Elem = <msg></msg>
你可以试试这个:
def makeMsg(t: Option[String]) = <msg text={t orNull} />

如果属性值为null,则不会将其添加到元素.

更新

更好!如果你添加这个隐式转换:

import xml.Text
implicit def optStrToOptText(opt: Option[String]) = opt map Text

你可以这样使用t:

def makeMsg(t: Option[String]) = <msg text={t} />

这是REPL会话:

scala> import xml.Text
import xml.Text

scala> implicit def optStrToOptText(opt: Option[String]) = opt map Text
optStrToOptText: (opt: Option[String])Option[scala.xml.Text]

scala> def makeMsg(t: Option[String]) = <msg text={t} />
makeMsg: (t: Option[String])scala.xml.Elem

scala> makeMsg(Some("hello"))
res1: scala.xml.Elem = <msg text="hello"></msg>

scala> makeMsg(None)
res2: scala.xml.Elem = <msg ></msg>

这是因为scala.xml.UnprefixedAttribute具有接受Option [Seq [Node]]作为值的构造函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读