如何根据选项添加或不添加 XML 属性? [英] How do I add an XML attribute, or not, depending on an Option?
本文介绍了如何根据选项添加或不添加 XML 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了一个 makeMsg 函数,但我不喜欢它 - 基于 Option.isDefined 进行区分似乎真的不符合 Scala 风格.你能做得更好吗?
I have written a makeMsg function but I don't like it - it just seems really un-Scala-ish to discriminate based on Option.isDefined. Can you make it better?
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
- 它不会被添加到元素中.
if attribute value is null
- it will not be added to the element.
更好!如果您将添加此隐式转换:
Even better! If you will add this implicit convertion:
import xml.Text
implicit def optStrToOptText(opt: Option[String]) = opt map Text
你可以像这样使用t
:
def makeMsg(t: Option[String]) = <msg text={t} />
这是 REPL 会话:
Here is REPL session:
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]]
作为值的构造函数.
This works because scala.xml.UnprefixedAttribute
has constructor that accepts Option[Seq[Node]]
as value.
这篇关于如何根据选项添加或不添加 XML 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文