使用Scala查找具有匹配某个值的属性的所有节点

3

我曾在此前看到过以下例子,目标是返回包含具有值Y的id属性的所有节点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) 

我正在使用Scala 2.7,每次打印返回值时总是空的。有人可以帮忙吗? 抱歉如果我复制了另一个线程...但是认为如果我发布一个新的将更加可见?
1个回答

8
根据 Node ScalaDocattribute 的定义如下:
 def attribute(key: String):Option[Seq[Node]]

因此,您应该修改您的代码如下:
def attributeEquals(name: String, value: String)(node: Node) =  
{  
    node.attribute(name).filter(_.text==value).isDefined // *text* returns a text representation of the node 
} 

但是为什么不直接实现同样简单的功能呢:
scala> (xml descendant_or_self) filter{node => (node \ "@class").text == "test"}
res1: List[scala.xml.Node] = List(<span class="test">hello</span>, <div class="test"><p>hello</p></div>)

非常感谢,这正是它所缺少的! :) - silverman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接