0

我有一个类,我希望在 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() 行下方可以很好地打印它

4

1 回答 1

1

对于这种逻辑,您可以将其表示为 NodeSeq,而不是将其与 xml 文字混合。

就像是:

        case None =>
          NodeSeq.fromSeq(Seq(<Name>{text.value}</Name>, getShortName().orNull, <Language>{robName.Language_Code}</Language>))
于 2020-09-18T20:13:39.337 回答