我有以下示例 xml:
<data>
<products>
<product>
<section>Red Section</section>
<images>
<image>img.jpg</image>
<image>img2.jpg</image>
</images>
</product>
<product>
<section>Blue Section</section>
<images>
<image>img.jpg</image>
<image>img3.jpg</image>
</images>
</product>
<product>
<section>Green Section</section>
<images>
<image>img.jpg</image>
<image>img2.jpg</image>
</images>
</product>
</products>
</data>
我知道如何在 Clojure 中解析它
(require '[clojure.xml :as xml])
(def x (xml/parse 'location/of/that/xml'))
这将返回一个描述 xml 的嵌套映射
{:tag :data,
:attrs nil,
:content [
{:tag :products,
:attrs nil,
:content [
{:tag :product,
:attrs nil,
:content [] ..
当然可以使用标准 Clojure 函数遍历此结构,但它可能会变得非常冗长,尤其是与使用 XPath 查询它相比。有没有帮助程序可以遍历和搜索这样的结构?例如,我怎样才能
- 获取全部列表
<product>
- 只获取其产品
<images>
标签包含一个<image>
文字为“img2.jpg”
- 获得其产品
section
是“红色部分”
Thanks
Using Zippers http://en.wikipedia.org/wiki/Zipper_%28data_structure%29 from data.zip http://clojure.github.com/data.zip/这是您的第二个用例的解决方案:
(ns core
(:use clojure.data.zip.xml)
(:require [clojure.zip :as zip]
[clojure.xml :as xml]))
(def data (zip/xml-zip (xml/parse PATH)))
(def products (xml-> data :products :product))
(for [product products :let [image (xml-> product :images :image)]
:when (some (text= "img2.jpg") image)]
{:section (xml1-> product :section text)
:images (map text image)})
=> ({:section "Red Section", :images ("img.jpg" "img2.jpg")}
{:section "Green Section", :images ("img.jpg" "img2.jpg")})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)