XML element with optional attribute

101 views
Skip to first unread message

Russ P.

unread,
Mar 24, 2017, 2:01:33 AM3/24/17
to scala-user
Suppose I am printing out an XML element like this:

  def toXML: xml.Elem = {

    <waypt name={name}>
      ...
      </waypt>
    }

The "name" attribute is a String and is optional (some waypoints have names and some don't). I want to show it only if it is nonempty. In other words, I don't want to see name=""

I just want the name attribute completely omitted if the name is an empty String.

How can I do that in the toXML method above? Thanks.

Naftoli Gugenheim

unread,
Mar 24, 2017, 2:48:56 AM3/24/17
to Russ P., scala-user
I don't know if there's a better solution, but Elem is a case class so you can add the attribute on afterwards using the copy method.

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Daniel Manchester

unread,
Mar 28, 2017, 11:49:24 PM3/28/17
to scala-user
Hi,

If you make "name" an Option[scala.xml.Text], I think the XML will be generated as you desire.

Dan

Russ Paielli

unread,
Mar 29, 2017, 1:18:36 AM3/29/17
to Daniel Manchester, scala-user
Nice. Thanks!


--
You received this message because you are subscribed to a topic in the Google Groups "scala-user" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/scala-user/vqLXM7clpqo/unsubscribe.
To unsubscribe from this group and all its topics, send an email to scala-user+unsubscribe@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages