我在 Nabble 上看到了下面的例子,其目标是返回所有包含 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 )
作为对此的扩展,人们将如何执行以下操作:查找包含任何包含 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"))
但它不起作用。我知道我可以使用模式匹配,但只是想看看我是否可以通过过滤来施展魔法。
干杯 - 埃德
最佳答案
首先,XML 在 Scala 中是文字,所以:
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
”和“defined
” .
最后,我个人更喜欢运算符风格的语法,特别是当你有一个现成的函数而不是匿名函数时,要传递给“filter
”:
val testResults = xml \\ "_" filter attributeValueEquals("test")
原始版本将“\\
”的运算符样式和“filter
”的点样式混合在一起,结果非常丑陋。
关于xml - 使用scala查找具有与特定值匹配的属性的所有节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1477215/