1

I need a way to add an XML attribute 'POSITON' to an XML element 'node' conditionally. Currently I'm doing the condition check first and then creating the node.

if (lvl == 2)
      node = <node COLOR={ color } CREATED={ epochTimeMillis } ID={ idGen } POSITION={ position } LINK={ link } MODIFIED={ epochTimeMillis } STYLE="bubble" TEXT={ f.getName() }>
               <edge COLOR={ color } STYLE={ style } WIDTH={ width }/>
             </node>
else
      node = <node COLOR={ color } CREATED={ epochTimeMillis } ID={ idGen } LINK={ link } MODIFIED={ epochTimeMillis } STYLE="bubble" TEXT={ f.getName() }>
               <edge COLOR={ color } STYLE={ style } WIDTH={ width }/>
             </node>
  }

3 Answers 3

3

Using "null" is not a good practice, but in this case it would help you:

scala> <root ta={ if (true) "true" else null } fa={ if (false) "false" else null } />
res0: scala.xml.Elem = <root ta="true" ></root>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it worked. I was earlier trying with "" but should have used null.
1

A slightly cleaner way to do the same thing @senia suggests is:

    val posOpt = if (lvl2) Some(myPosition) else None
    val xml = <mydata position={posOpt orNull}/>

Comments

0

One way is to create the snippet before:

val pos =
  if (lvl == 2) {
    "position = ..."
  } else {
    ""
  }

and to always insert it in the result.

This could by extended by using an Option with embedded map in combination with string interpolation.

val pos =
  if (lvl == 2) {
    Some(position)
  } else {
    None
  }

with

pos.map(v => s"position = $v")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.