0

Suppose I need to get the attribute value in Scala. I can assume that the attribute is a string (and if it is not this is an error).

Since the scala.xml API (MetaData.get(name: String):Option[Seq[Node]]) looks rather complex I wrote a helper function:

 def attributeValue(e: Elem, aname: String): Option[String] = for {
   seq <- e.attributes.get(aname)
   value <- seq.collectFirst {case Text(txt) => txt}
 } yield value

Does it make sense ? How would you change/fix this code

1 Answer 1

2

How about using the \ operator to extract attribute value:

  def attributeValue(e: Elem, attributeName: String): Option[String] =
    (e \ s"@$attributeName").collectFirst { case Text(txt) => txt }

Please note, in some cases you might want to simplify it even more (as shown below), however in this case the empty string will be returned if attribute is not found (which is probably not what you're after):

  def attributeValue(e: Elem, attributeName: String): String =
    (e \ s"@$attributeName").text
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Looks similar to e.attributes.get(aname).collectFirst{case Text(txt) => txt}. I thought that the for-comprehension improves readability.
BTW, I do not get why attributes.get returns Option of Seq[Node] instead of Option of String.

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.