From 1426d9cecf1b6123d0dffe44a8ab0dbf88a29707 Mon Sep 17 00:00:00 2001 From: Roberto Tyley Date: Tue, 27 Nov 2012 22:51:01 +0000 Subject: Add convenience attribute operator to NodeSeq Compared to the current method of reading the string text of an attribute: (x \ "@bar").text ...the new operator removes the need for a pair of parenthesis and shortens the overall expression by 7 chars : x \@ "bar" Discussion on scala-internals: https://groups.google.com/d/topic/scala-internals/BZ-tfbebDqE/discussion --- src/library/scala/xml/NodeSeq.scala | 5 +++++ test/files/jvm/xmlattr.scala | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/src/library/scala/xml/NodeSeq.scala b/src/library/scala/xml/NodeSeq.scala index decf60dad7..d2efc947b1 100644 --- a/src/library/scala/xml/NodeSeq.scala +++ b/src/library/scala/xml/NodeSeq.scala @@ -145,6 +145,11 @@ abstract class NodeSeq extends AbstractSeq[Node] with immutable.Seq[Node] with S } } + /** Convenience method which returns string text of the named attribute. Use: + * - `that \@ "foo"` to get the string text of attribute `"foo"`; + */ + def \@(attributeName: String): String = (this \ ("@" + attributeName)).text + override def toString(): String = theSeq.mkString def text: String = (this map (_.text)).mkString diff --git a/test/files/jvm/xmlattr.scala b/test/files/jvm/xmlattr.scala index d214642eb6..6423268ba7 100644 --- a/test/files/jvm/xmlattr.scala +++ b/test/files/jvm/xmlattr.scala @@ -6,6 +6,7 @@ object Test { UnprefixedAttributeTest() AttributeWithOptionTest() AttributeOutputTest() + AttributeOperatorTest() } object UnprefixedAttributeTest { @@ -60,4 +61,10 @@ object Test { } } + object AttributeOperatorTest { + def apply() { + val xml = + assert(xml \@ "bar" == "apple") + } + } } -- cgit v1.2.3