in regards of finding all nodes that have an attri

2020-07-19 05:00发布

问题:

I saw the following example disccussed here previously, 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) 

I am using Scala 2.7 and everytime the return printed value is always empty. Anyone could help on that ? Sorry if I am copying another thread... but thought it would be more visible if I posted a new one ?

回答1:

According to Node ScalaDoc, attribute is defined as follows:

 def attribute(key: String):Option[Seq[Node]]

Therefore, you should modify your code that way:

def attributeEquals(name: String, value: String)(node: Node) =  
{  
    node.attribute(name).filter(_.text==value).isDefined // *text* returns a text representation of the node 
} 

But why not just achieving the same simpler:

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


标签: xml scala