我有一个类,我希望在 xml 中添加一个条件 Elem,但我无法做到这一点。请帮忙。ShortName 块应该是有条件的。在调试时,我看到 get shortname 被执行。事实上,如果我尝试将其包装在一个虚拟标签 ( <dummy>{getShortName().get}</dummy>
) 中,一切正常。但我需要外面的条件。这是我的课:
import scala.xml.Elem
class MyClass(rob: ROB, scalaDTO: ScalaDTO, robStatus: Status) {
val myRob =
<FeatureNames>
{val allPoiNames = rob.Identity.Names.get.ROB_Name
allPoiNames.map(robName => {
if (!robName.Type.contains("Shortened")) {
<FeatureName CaseAutoCorrectionEnabled="true">
{robName.Text.map(text => {
val transType = text.Trans_Type
transType match {
case None => {
{
<Name>
{text.value}
</Name>
{
//Executes but does not get added
getShortName().getOrElse(null)
}
<Language>
{robName.Language_Code}
</Language>
}
}
case _ => {
<OtherName>
{text.value}
</OtherName>
}
}
})}
</FeatureName>
}
})}
</FeatureNames>
private def getShortName(): Option[Elem] = {
val condition = true
if (condition) {
Some(
<ShortName>ShortName</ShortName>
)
} else {
None
}
}
override def toString: String = {
val prettyPrinter = new scala.xml.PrettyPrinter(150, 2)
prettyPrinter.format(scala.xml.Utility.trim(myRob))
}
}
我的输出看起来像:
<FeatureNames>
<FeatureName CaseAutoCorrectionEnabled="true">
<Language>ENF</Language>
<OtherName>The Name</OtherName>
</FeatureName>
</FeatureNames>
注意缺少名称标签,将其移到 getShortName() 行下方可以很好地打印它