使用scala查找具有与某个值匹配的属性的所有节点 [英] Find all nodes that have an attribute that matches a certain value with scala

查看:199
本文介绍了使用scala查找具有与某个值匹配的属性的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在

I saw the following example on Nabble, where the goal was to return all nodes that contain an attribute with an id of X that contains a value Y:

//find all nodes with an attribute "class" that contains the value "test"
val xml = XML.loadString( """<div>
<span class="test">hello</span>
<div class="test"><p>hello</p></div>
</div>""" )

def attributeEquals(name: String, value: String)(node: Node) = 
{ 
    node.attribute(name).filter(_==value).isDefined
}

val testResults = (xml \\ "_").filter(attributeEquals("class","test")) 
//prints: ArrayBuffer(
//<span class="test">hello</span>, 
//<div class="test"><p>hello</p></div>
//) 
println("testResults: " + testResults ) 

对此进行了扩展:如何执行以下操作:查找包含任何包含Y值的属性的所有节点:

As an extension to this how would one do the following: Find all nodes that contain any attribute that contains a value of Y:

//find all nodes with any attribute that contains the value "test"
val xml = XML.loadString( """<div>
 <span class="test">hello</span>
 <div id="test"><p>hello</p></div>
 <random any="test"/></div>""" )
 //should return: ArrayBuffer(
 //<span class="test">hello</span>, 
 //<div id="test"><p>hello</p></div>, 
 //<random any="test"/> )

我当时以为可以使用_:

I was thinking I could use a _ like so:

val testResults = (xml \\ "_").filter(attributeEquals("_","test")) 

但是它不起作用.我知道我可以使用模式匹配,但是只是想看看我是否可以通过过滤来做一些魔术.

But it doesn't work. I know I can use pattern matching, but just wanted to see if I could do some magic with the filtering.

干杯-Ed

推荐答案

首先,XML是Scala中的文字,因此:

First, XML are literals in Scala, so:

val xml = <div><span class="test">hello</span><div class="test"><p>hello</p></div></div>

现在,关于这个问题:

def attributeValueEquals(value: String)(node: Node) = {
     node.attributes.exists(_.value.text == value)
}

实际上,对于原始问题,我也会使用"exists"代替"filter"和"defined".

In fact, I'd have used "exists" instead of "filter" and "defined" for the original problem as well.

最后,我个人更喜欢使用运算符样式的语法,尤其是当您有一个就绪函数而不是匿名函数时,请传递给"filter":

Finally, I personally prefer operator style syntax, particularly when you have a ready function, instead of an anonymous one, to pass to "filter":

val testResults = xml \\ "_" filter attributeValueEquals("test")

原始混合了"\\"和"filter"的点运算符样式,结果非常难看.

The original mixes operator style for "\\" and dot style for "filter", which ends up quite ugly.

这篇关于使用scala查找具有与某个值匹配的属性的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆