开发者

Scala XML Pattern matching and Attributes

First of all: I'm at Scala 2.8

I have a slight issue while using pattern matching on XML elements. I know I can do something like this:

val myXML = <a><b>My Text</b></a>
myXML match {
    case <a><b>{theText}</b></a> => println(theText)
    case _ =>
}

This is the sort of example I find everywhere on the net and in both of my Scala books. But what if I want to match on an XML element depending on an attribute?

val myXML = <a><b type="awesome">An awesome Text!</b></a>
myXML match {
    case <a><b type={textType}>{theText}</b><a> => println("An %s text: %s".format(textType, theText))
    case _ => 
}

The compiler will throw an error: in XML literal: '>' expected instead of 't' at me, indicating that I cannot use attributes because the compiler expected the element tag to be c开发者_如何学编程losed. If I try to match an XML element with a fixed attribute, without curly braces, the same error raises.

So my question is simple: How can I do such a match? Do I have to create an Elem for the match instead of using those nice literals? And if: What is the best way to do it?


Handling attributes is way more of a pain that it should be. This particular example shows, in fact, that Scala doesn't deconstruct XMLs the same way it constructs them, as this syntax is valid for XML literals. Anyway, here's a way:

myXML match { 
  case <a>{b @ <b>{theText}</b>}</a> => 
    println("An %s text: %s".format(b \ "@type", theText))
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜