Search code examples
scalascala-xml

Scala XML Elem Not Showing Up


I have a class where I want a conditional Elem in xml to be added, but I am unable to do this. Please help. The ShortName block is supposed to be conditional. While debugging I see that get shortname gets executed. In fact if I try wrapping that in a dummy tag (<dummy>{getShortName().get}</dummy> ) everything works. But I need the condition outside. Here's my class:

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))
  }
}

My output looks like:

<FeatureNames>
  <FeatureName CaseAutoCorrectionEnabled="true">
    <Language>ENF</Language>
    <OtherName>The Name</OtherName>
  </FeatureName>
</FeatureNames> 

Note the Missing Name Tag,moving it below the getShortName() line prints it fine


Solution

  • For this kind of logic, you can express it as a NodeSeq instead of mixing it in with xml literals.

    Something like:

            case None =>
              NodeSeq.fromSeq(Seq(<Name>{text.value}</Name>, getShortName().orNull, <Language>{robName.Language_Code}</Language>))