我想在 Apache Batik DOM 中查询与 CSS 选择器匹配的元素。
Batik 是否提供以下任何浏览器 DOM 方法的替代方法?
我想在 Apache Batik DOM 中查询与 CSS 选择器匹配的元素。
Batik 是否提供以下任何浏览器 DOM 方法的替代方法?
好的,这是我设法放在一起的解决方案。它是用 Clojure 而不是 Java 编写的,但重要的部分是:
(def ^:private condition-factory
(CSSConditionFactory. nil "class" nil "id"))
(defn- parse-selector [selector]
(let [parser (Parser.)]
(doto parser
(.setSelectorFactory CSSSelectorFactory/INSTANCE)
(.setConditionFactory condition-factory))
(.parseSelectors parser selector)))
(defn- matches?
([selector element] (matches? selector element ""))
([selector element pseudo]
(let [length (.getLength selector)]
(loop [i 0]
(if (< i length)
(if (.. selector (item i) (match element pseudo))
true
(recur (inc i)))
false)))))
(defn selection-seq [root selector]
(let [selector (parse-selector selector)
iterator (.createNodeIterator (TraversalSupport.)
(.getOwnerDocument root)
root
NodeFilter/SHOW_ELEMENT
(reify NodeFilter
(acceptNode [_ element]
(if (matches? selector element)
NodeFilter/FILTER_ACCEPT
NodeFilter/FILTER_REJECT)))
false)
node-seq ((fn step []
(lazy-seq
(when-let [node (.nextNode iterator)]
(cons node (step))))))]
;; Iterator always returns the reference node, so match it.
(when-let [node (first node-seq)]
(if (matches? selector (first node-seq))
node-seq
(next node-seq)))))