【问题标题】:Lift: How to select a Node in a NodeSeq by attribute and value?Lift:如何通过属性和值在 NodeSeq 中选择一个节点?
【发布时间】:2012-05-29 21:41:39
【问题描述】:

我有一个 NodeSeq 对象,并且想要选择一个标有属性的给定节点。例如,假设 NodeSeq 中有一个标签 <div id="content">...</div>

我尝试使用 NodeSeq 上的 \\ 方法以及过滤器进行选择。

假设 seq 是我的 NodeSeq 对象。

seq \\ "div" 有效,但这会选择所有 <div> 元素。

seq.filter(_.attribute("id").equals("content")) 根本不选择任何节点,结果列表为空。

如何选择此节点?

【问题讨论】:

    标签: scala select attributes lift nodes


    【解决方案1】:

    试试

    scala> var x= <b>
     | <h id="bla"/>
     | <h id="blub"/>
     | </b>
    
    x \\ "h" filter (h=>(h \ "@id" toString) == "bla")
    

    这应该可行。

    【讨论】:

    • 谢谢,这很好用。 :-) 我想知道,为什么它不适用于 _.attribute("id").equals("content") 方法。
    • 如果你尝试 x \\ "h" map (_ \ "@id" ) res1: scala.collection.immutable.Seq[scala.xml.NodeSeq] = List(bla, blub)类型是 NodeSeq 所以它不等于字符串 ;)
    • 这可能更好:x \\ "h" map (_ \ "@id" text ) res2: scala.collection.immutable.Seq[String] = List(bla, blub)跨度>
    【解决方案2】:

    或者,您可以尝试以下方法:

    seq.filter(_.attribute("id").exists(_.text.equals("content")))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多