scala xml模式匹配同名元素

时间:2012-01-05 00:45:22

标签: scala

假设我有以下xml:

val xml = 
  <countries>
    <country isoCode="AU">Australia</country>
    <country isoCode="GB">Great Britain</country>
  </countries>

我如何使用isoCode =“AU”模式匹配元素?我只提出了以下解决方案:

xml match {
  case <countries>{cs @ _*}</countries> => {
    for(c <- cs) {
      c match {
        case cnode @ <country>{name}</country> if (cnode \ "@isoCode").toString == "AU" => println("I like " + name)
        case _ => Unit
      }
    }
  }
}

由于

1 个答案:

答案 0 :(得分:1)

mtsz是正确的,这只是它在Scala Xml中的完成方式。如果你对替代品开放,那么Scales提供直接的xpath语法(和基于Jaxen的字符串)和属性上的模式匹配:

import scales.utils._
import ScalesUtils._
import scales.xml._
import ScalesXml._

import TextFunctions.value

val xml = 
  (<countries>
    <country isoCode="AU">Australia</country>
    <country isoCode="GB">Great Britain</country>
  </countries>).asScales.rootElem

val couldContainAU = top(xml). *("countries"). 
    \*("country"). 
    \@{ a => a.name == ("isoCode"l) && a.value == "AU"}.\^

couldContainAU.foreach{ country => println( "got " + value(country) ) }

// or collect all isoCodes via pattern matching

val IsoMatcher = ElemMatcher("country", "isoCode")

for{ countries <- top(xml) * "countries"
     country <- countries \* "country"
 } elem(country) match {
  case IsoMatcher(elem, Attr(iso) :: Nil) => println(iso+" => "+value(country))
  case _ => println("oops")
}

NB

\@{ a => a.name == ("isoCode"l) && a.value == "AU"}

将可以通过

\@("isoCode") .*@(_.value == "AU")

在下一个RC中也是如此。