本文介绍了Scala XML 模式匹配和属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先:我在 Scala 2.8

First of all: I'm at Scala 2.8

我在 XML 元素上使用模式匹配时遇到了一个小问题.我知道我可以做这样的事情:

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 _ =>
}

这是我在网上和我的两本 Scala 书籍中随处可见的例子.但是如果我想根据属性匹配一个 XML 元素怎么办?

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 _ =>
}

编译器会抛出一个 error: in XML literal: '>'预期而不是 't' 在我身上,表明我不能使用属性,因为编译器希望元素标记被关闭.如果我尝试将 XML 元素与固定属性匹配,而没有花括号,则会引发相同的错误.

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.

所以我的问题很简单:我怎样才能进行这样的匹配?我是否必须为匹配创建一个 Elem 而不是使用那些漂亮的文字?如果:最好的方法是什么?

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?

推荐答案

处理属性比它应该的更痛苦.事实上,这个特殊的例子表明,Scala 并没有像构造 XML 那样解构 XML,因为这语法 is 对 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 thissyntax 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))
}

这篇关于Scala XML 模式匹配和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:22