我之前看到过这里讨论的以下示例,其目标是返回包含 id 为 X 且包含值 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)
我使用的是 Scala 2.7,每次返回打印值始终为空。任何人都可以帮忙吗?
抱歉,如果我复制另一个线程...但认为如果我发布一个新线程,它会更明显?
根据NodeScala文档 http://www.scala-lang.org/api/current/scala/xml/Node.html, attribute
定义如下:
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>)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)