2011-09-27 21 views
5

次のように簡略化する方法はありますか?または別の関数で定型文を減らすことはできますか?Scala XML、親が属性値と一致するノードを取得

scala> val ns = <foo><bar id="1"><tag>one</tag><tag>uno</tag></bar><bar id="2"><tag>two</tag><tag>dos</tag></bar></foo> 
ns: scala.xml.Elem = <foo><bar id="1"><tag>one</tag><tag>uno</tag></bar><bar id="2"><tag>two</tag><tag>dos</tag></bar></foo> 

scala> (ns \\ "bar" filterNot{_ \\ "@id" find { _.text == "1" } isEmpty}) \\ "tag" 
res0: scala.xml.NodeSeq = NodeSeq(<tag>one</tag>, <tag>uno</tag>) 

答えて

15

私はわずかな改善を見つけることができる、find/isEmptyテストはexistsに置き換えることができます:

(ns \\ "bar" filter { _ \\ "@id" exists (_.text == "1") }) \\ "tag" 

コメントを明確にした後、編集:

本当にいいアイデアです!サイズの場合はこれを試してください:

import xml._ 

implicit def richNodeSeq(ns: NodeSeq) = new { 

    def \@(attribMatch: (String, String => Boolean)): NodeSeq = 
    ns filter { _ \\ ("@" + attribMatch._1) exists (s => attribMatch._2(s.text)) } 

} 

ns \\ "bar" \@ ("id", _ == "1") \\ "tag" 

属性値の比較をハードコードする代わりに、述語を使用しました。

+1

ありがとうございます。私が本当に探しているのは、フィルター{_ \\ "@id"が存在する(_.text == "1")})のセレクターを作成する方法です。次に、(x \\ "bar" \ @( "@id"、 "1")\\ "tag" – eptx

+0

私はあなたのアイデアが好きです。 – Lachlan

関連する問題