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

前端 未结 5 1116
遥遥无期
遥遥无期 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:38

    First, XML are literals in Scala, so:

    val xml = 
    hello

    hello

    Now, as to the problem:

    def attributeValueEquals(value: String)(node: Node) = {
         node.attributes.exists(_.value.text == value)
    }
    

    In fact, I'd have used "exists" instead of "filter" and "defined" for the original problem as well.

    Finally, I personally prefer operator style syntax, particularly when you have a ready function, instead of an anonymous one, to pass to "filter":

    val testResults = xml \\ "_" filter attributeValueEquals("test")
    

    The original mixes operator style for "\\" and dot style for "filter", which ends up quite ugly.

提交回复
热议问题