Michael
Michael

Reputation: 42100

Attribute value of XML node in Scala

Suppose I am writing a function (Node, String) => Option[String] to get attribute value by attribute name from a given node.

def getAttributeValue(node: Node, attributeName: String): Option[String] = {
  val txt = (node \ ("@" + attributeName)).text
  if (txt.isEmpty) None else Some(txt)
}

Does it make sense ? How would you fix/improve it ?

Upvotes: 0

Views: 731

Answers (1)

Kolmar
Kolmar

Reputation: 14224

Scala has methods attribute defined on Node class, but they return Option[Seq[Node]], which requires further processing to get a String.

So I'm currently using something very similar in my code:

implicit class XmlEnhancements(node: Node) {
  def attributeOpt(attribute: String): Option[String] =
    node.attribute(attribute) flatMap (_.headOption) map (_.text)
}

Also, as Scala itself defines method def \@(attributeName: String): String on the xml.Node class, I believe it's also OK to define this attributeOpt under \@? alias:

implicit class XmlEnhancements(node: Node) {
  def \@?(attribute: String): Option[String] =
    node \@ attribute match {
      case "" => None
      case s => Some(s)
    }
}

Upvotes: 2

Related Questions