English 中文(简体)
找出所有具有某种价值与微粒相当的特性的节点
原标题:Find all nodes that have an attribute that matches a certain value with scala
  • 时间:2009-09-25 13:12:45
  •  标签:

我在Nabble上看到了以下例子,其目标是归还所有含有X面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面面

//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值的属性节点:

//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"/> )

我想我可以这样说:

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

但它没有工作。 我知道我可以使用配对模式,但我只想看到,我是否能够用过滤器做一些魔.。

Cheers - Ed

最佳回答

第一,SML在Schala是字面的,因此:

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和“下定义的”处理原始问题。

最后,我个人喜欢经营人歌唱,特别是当你有准备的功能,而不是匿名功能时,要通过“filter<<<>/code>:

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

”和“filter”的原始组合式操作体格相当高。

问题回答

由于这种比较,《刑法》在问题中与第2.8条相对应。

(_ == value)
Needs to be replaced with (_.text == value) or (_ == Text(value)) or change type of value from String to Text.

在丹尼尔的回答中,<代码>(_. 价值 = = 价值)需要替换为<代码>(_. 数值.text = 价值)。

以前的解决办法对我来说不可行,因为它们都希望到<>任何<>>>。 价值相当于。 如果你想找一个具有价值的Particular属性,我的解决办法是:

def getByAtt(e: Elem, att: String, value: String) = {
    def filterAtribute(node: Node, att: String, value: String) =  (node  ("@" + att)).text == value   
    e \ "_" filter { n=> filterAtribute(n, att, value)} 
}

之后

getByAtt(xml, "class", "test")

这将区分<条码>级=“测试”和<条码>>>=“测试”

我对Schala说了很新的话,我提议你这样做,但我不相信这是最好的解决办法:

def attributeValueEquals(value: String)(node: Node) = {
  node.attributes.foldLeft(false)((a : Boolean, x : MetaData) => a | (x.value == value))
}

val testResults = (xml \ "_").filter(attributeValueEquals("test")) 
println("testResults: " + testResults )

// prints: testResults: ArrayBuffer(<span class="test">hello</span>, 
// <div id="test"><p>hello</p></div>, 
// <random any="test"></random>)
def nodeHasValue(node:Node,value:String) = node.attributes.value != null && node.attributes.value.contains(value)

(x \ "_").filter( nodeHasValue(_,"test"))




相关问题
热门标签