0

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 ?

1
  • Makes sense to me. One idea could be to provide an implicit class adding the attribute getter onto Node to get a more concise way to call the method. Something like: node.attribute(name) Commented May 11, 2015 at 16:50

1 Answer 1

2

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)
    }
}
Sign up to request clarification or add additional context in comments.

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.