您可以使用Tupelo Forest 库处理树状数据结构来解决此问题。除了显式搜索,它还可以使用通配符,如zsh
. 文档正在进行中,但这将使您了解您可以做什么:
(dotest
(with-forest (new-forest)
(let [xml-str "<top>
<group>
<group>
<item>
<number>1</number>
</item>
<item>
<number>2</number>
</item>
<item>
<number>3</number>
</item>
</group>
<item>
<number>0</number>
</item>
</group>
</top>"
enlive-tree (->> xml-str
java.io.StringReader.
en-html/xml-resource
only)
root-hid (add-tree-enlive enlive-tree)
; Removing whitespace nodes is optional; just done to keep things neat
blank-leaf-hid? (fn fn-blank-leaf-hid? ; whitespace pred fn
[hid]
(let [node (hid->node hid)]
(and (contains-key? node :value)
(ts/whitespace? (grab :value node)))))
blank-leaf-hids (keep-if blank-leaf-hid? (all-leaf-hids)) ; find whitespace nodes
>> (apply remove-hid blank-leaf-hids) ; delete whitespace nodes found
你真正关心的部分在这里。有两种方法可以搜索嵌套节点。
- 第一种方法指定从根开始的显式路径
第二个使用:**
像 zsh 这样的通配符,它匹配零个或多个目录。
; Can search for inner `div` 2 ways
result-1 (find-paths root-hid [:top :group :group]) ; explicit path from root
result-2 (find-paths root-hid [:** :group :item :number]) ; wildcard path that ends in :number
]
对于 cast (1),我们看到我们只找到了项目 1、2 和 3:
; Here we see only the double-nested items 1, 2, 3
(is= (spyx-pretty (format-paths result-1))
[[{:tag :top}
[{:tag :group}
[{:tag :group}
[{:tag :item} [{:tag :number, :value "1"}]]
[{:tag :item} [{:tag :number, :value "2"}]]
[{:tag :item} [{:tag :number, :value "3"}]]]]]] )
对于情况(2),我们不仅找到了双重嵌套项,还找到了单嵌套项0
:
; Here we see both the double-nested items & the single-nested item 0
(is= (spyx-pretty (format-paths result-2))
[[{:tag :top}
[{:tag :group} [{:tag :item} [{:tag :number, :value "0"}]]]]
[{:tag :top}
[{:tag :group}
[{:tag :group} [{:tag :item} [{:tag :number, :value "1"}]]]]]
[{:tag :top}
[{:tag :group}
[{:tag :group} [{:tag :item} [{:tag :number, :value "2"}]]]]]
[{:tag :top}
[{:tag :group}
[{:tag :group} [{:tag :item} [{:tag :number, :value "3"}]]]]]])
)))
您没有指定所需的下游处理。Tupelo.Forest
能够将输出转换为hiccup
和enlive
格式,加上它自己的打嗝式bush
格式和生动的tree
格式。