Michael
Michael

Reputation: 42050

Retrieve XML attribute value in Scala

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

Upvotes: 0

Views: 1043

Answers (1)

Norbert Radyk
Norbert Radyk

Reputation: 2618

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

Upvotes: 2

Related Questions