簡體   English   中英

scala節點匹配案例

[英]scala node match case

這工作:

<a>apple</a>

node match {
  case <a>{contents}</a> => "It's an a: "+ contents
  case _ => "It's something else."
}

我怎么能修改這個例子,以便它只匹配一個帶有標簽“a”和屬性id = 2的節點:如下所示:

<a id="2">apple</a>

node match {
  case <a id="2">{contents}</a> => "It's an a: "+ contents
  case _ => "It's something else."
}

但這不編譯。

這是一種方法:

node match {
  case a @ <a>{contents}</a> if (a \ "@id").text == "2" => "It's an a: " + contents
  case _ => "It's something else."
}

還有一種方法,就是為了它。

<a id="2">apple</a> match {
  case Node("a", Attribute("id", Text("2"), _), Text(contents)) => contents
}

但是,對多個屬性不起作用。

看起來你需要完整的XPath支持來編寫像“a [id ='2']”這樣的查詢

Scala秤是可用選項之一。

但除了菲利普的答案,我可以建議這個查詢

import scala.xml.Text
val node = <a id="2">apple</a>
(node  \\"a" \"@id").text match {
  case "2" => "It's an a: "+ (node \\"a").text
  case _ => "It's something else."
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM