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 ?
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>)
精彩评论