我在Nabble上看到以下示例,其目標是返回包含ID爲X的屬性的所有節點,其中包含值Y:查找具有與scala匹配的特定值的屬性的所有節點
//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"))
但它不起作用。我知道我可以使用模式匹配,但只是想看看我是否可以通過過濾來做一些魔術。
乾杯 - 埃德
之間我發現XPath語言更簡單的https://github.com/nrinaudo/kantan。xpath並且在Scala中編譯時安全 –