【问题标题】:How to use selector negation (but ...) in Enlive on a more complex HTML snippet?如何在更复杂的 HTML 片段上使用 Enlive 中的选择器否定(但...)?
【发布时间】:2011-10-24 10:12:59
【问题描述】:

我有一个类似于以下内容的 HTML sn-p:

<div id="root">
    <div id="A" attrib_2="bar"></div>
    <div id="B" attrib_2="baz">
        <div id="H" attrib_1="gnu">
            <p>
                <div id="F" attrib_2="baz"></div>
            </p>
        </div>
    </div>
    <div id="C" attrib_2="owl"></div>
    <div id="D" attrib_2="uhu"></div>
    <div id="E" attrib_2="boom"></div>
</div>

现在,我想选择所有具有 attrib_2 (*[attrb_2]) 的 sn-ps,不包括具有 attrib_1 集的节点的后代。可以有更多带有任意标签的嵌套级别(如本例中的&lt;p&gt;)。使用 Enlive (http://enlive.cgrand.net/),我已经尝试过类似的方法:

(select snippet [(but (attr? :attrib_1)) (attr? :attrib_2)])

但这不起作用,因为否定 (but (attr? :attrib_1)) 也匹配 &lt;p&gt; 标记。有没有办法用给定的选择器谓词 (http://enlive.cgrand.net/syntax.html) 来表达这一点,还是我必须自己写一个?

提前致谢

-乔辰

【问题讨论】:

  • 语义上,内部attrib_2 是否应该有所不同? [编辑:对不起,我在考虑类,这实际上可能有助于识别不同的范围而不是属性。]
  • 这个用例是从网页中提取 RDFa 元素,如w3.org/TR/rdfa-api 中所述。我想在具有“typeof”属性的标签中搜索“property”属性。但只有“直接”的后代。具有“typeof”属性的后代会打开一个要评估的新上下文。
  • 你到底为什么要标记这个 CSS?我对 Enlive 不是很熟悉,但是如果你想用纯 CSS 来实现这个解决方案,是有可能的。
  • 我用 CSS 标记了这个,因为 Enlive 使用相同的选择器语义。你如何在纯 CSS 中实现这一点?

标签: html css clojure enlive


【解决方案1】:

只是为了争论,你不能这样做吗:

<div id="whatever" class="attrib_2 bar"></div>

从语义上看,这似乎会更好,但是我不知道您使用的是什么系统,或者您的最终目的是什么。但是,如果您要使用类,CSS 将非常简单:

div.attrib.bar {
    something:else;
}

【讨论】:

    【解决方案2】:

    您必须编写自己的选择器:

    (def parents 
      (zip-pred (fn [loc pred]
                  (some pred (take-while identity (iterate zip/up loc))))))
    

    (未经测试)

    然后

    (select snippet [[(attr? :attrib_2) (but (parents (attr? :attrib_1))]])
    

    应该可以。

    【讨论】:

    • 如果你只想遍历父母,你应该在谓词定义中使用(iterate zip/up (zip/up loc))
    • 请注意 zip-pred 现在采用 1-arity 函数,因此 pred 应作为 parents 的参数。
    【解决方案3】:
    #root #a attrib_2{}
    #root #b attrib_2{}
    #root #c attrib_2{}
    #root #d attrib_2{}
    #root #e attrib_2{}
    

    这将选择根 div 内 css 中的所有 attrib2 sn-ps。

    【讨论】:

      猜你喜欢
      • 2013-01-04
      • 2023-03-09
      • 1970-01-01
      • 2014-10-28
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      • 1970-01-01
      相关资源
      最近更新 更多