Find all nodes that have an attribute that matches a certain value with scala

前端 未结 5 1061
遥遥无期
遥遥无期 2021-02-08 04:00

I saw the following example on Nabble, 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         


        
5条回答
  •  佛祖请我去吃肉
    2021-02-08 04:47

    The previous solutions didn't work for me because they all look for any value that matches. If you want to look for a particular attribute with a value, here is my solution:

    def getByAtt(e: Elem, att: String, value: String) = {
        def filterAtribute(node: Node, att: String, value: String) =  (node \ ("@" + att)).text == value   
        e \\ "_" filter { n=> filterAtribute(n, att, value)} 
    }
    

    And then

    getByAtt(xml, "class", "test")
    

    This will differentiate between class="test" and "notclass="test"

提交回复
热议问题