Scala XML 模式匹配和属性
首先:我使用的是 Scala 2.8,
在对 XML 元素使用模式匹配时遇到了一个小问题。我知道我可以做这样的事情:
val myXML = <a><b>My Text</b></a>
myXML match {
case <a><b>{theText}</b></a> => println(theText)
case _ =>
}
这是我在网上和我的两本 Scala 书中随处可见的示例。但是,如果我想根据属性匹配 XML 元素怎么办?
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 _ =>
}
编译器将抛出一个 错误:在 XML 文字中: '>' Expected 而不是我的 't'
,表明我无法使用属性,因为编译器期望元素标记关闭。如果我尝试将 XML 元素与固定属性(不带花括号)进行匹配,则会出现相同的错误。
所以我的问题很简单:我怎样才能进行这样的匹配?我是否必须为匹配创建一个 Elem
而不是使用那些漂亮的文字?如果:最好的方法是什么?
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 closed. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
处理属性本来应该是一件痛苦的事情。事实上,这个特定的示例表明,Scala 不会像构造 XML 那样解构 XML,因为
语法对于 XML 文字有效。无论如何,这里有一个方法:
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: