a convenience method for xml.NodeSeq: \@ operator to get attribute string value

507 views
Skip to first unread message

Roberto Tyley

unread,
Nov 24, 2012, 10:36:38 AM11/24/12
to scala-i...@googlegroups.com

(Not a weighty question, however the Scala pull-request policy directed me here, so...)

I often find myself adding an \@ operator to NodeSeq when I'm parsing xml, so I thought it might be generally useful enough to warrant adding to Scala core.

If you have an xml element defined:

scala> val x = <foo bar="apple" />
x: scala.xml.Elem = <foo bar="apple"></foo>

...the current code for getting the attribute string value looks like this:

scala> (x \ "@bar").text
res2: String = apple

The new operator removes the need for a pair of parenthesis and shortens the overall expression by 7 chars :

scala> x \@ "bar"
res3: String = apple

It's a pretty minor contribution, but makes my code look nicer at least. Is there anything I should do before submitting this as a pull-request?

best regards,
Roberto Tyley

--
// as an implicit

import xml.NodeSeq

object XmlSweetener {

  class NodeSeqExtended(original: NodeSeq) {
    def \@(attributeName: String): String = (original \ ("@" + attributeName)).text
  }

  implicit def nodseq2extended(x: NodeSeq) = new NodeSeqExtended(x)
}



p...@razie.com

unread,
Nov 24, 2012, 10:56:08 AM11/24/12
to scala-i...@googlegroups.com, scala-i...@googlegroups.com
+1 ...if there is voting...

Sent from my iPad

Adriaan Moors

unread,
Nov 25, 2012, 5:10:12 PM11/25/12
to scala-i...@googlegroups.com
On Sat, Nov 24, 2012 at 7:36 AM, Roberto Tyley <robert...@gmail.com> wrote:
It's a pretty minor contribution, but makes my code look nicer at least. Is there anything I should do before submitting this as a pull-request?
I think you took the right approach. Have a discussion on the mailing list, then submit a PR and continue the discussion/review there.

It's also okay to open a PR directly for contributions like this.

thanks!
adriaan

Roberto Tyley

unread,
Nov 27, 2012, 5:58:52 PM11/27/12
to scala-i...@googlegroups.com
Thanks - I've now submitted this as a pull request:


best regards,
Roberto
Reply all
Reply to author
Forward
0 new messages