Scala XML,获取父级属性值匹配的节点

Scala XML,获取父级属性值匹配的节点,xml,scala,xpath,Xml,Scala,Xpath,有没有办法简化以下内容?或者用另一个函数减少样板代码 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.El

有没有办法简化以下内容?或者用另一个函数减少样板代码

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>)
scala>val ns=oneunotowos
ns:scala.xml.Elem=oneunotowos
scala>(ns\\“bar”filterNot{{u\\“@id”find{{uu.text==“1”}isEmpty})\\“tag”
res0:scala.xml.NodeSeq=NodeSeq(一个,uno)

我只能找到一个小的改进,可以用
exists
替换
find
/
isEmpty
测试:

(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"

我使用谓词而不是硬编码属性值比较。

最好的方法是定义隐式类:

   object XmlE {
    implicit class XmlE(val xml: NodeSeq) extends AnyVal {
         def \@(attr: (String, String => Boolean)): NodeSeq = {
             xml filter {
                _ \ ("@" + attr._1) exists (s => attr._2(s.text))
                         }
                    }
            }
   }
然后从另一个类中使用它:

import XmlE._
.....

谢谢你的改进。我真正想寻找的是一种为过滤器{u\\\\“@id”存在({.text==“1”)})创建选择器的方法,然后它看起来像(x\\“bar”\@(@id”,“1”)\\\“tag”我喜欢你的想法。我已经用一种可能的解决方案编辑了我的答案。