在Clojure中搜索xml [英] Searching xml in Clojure

查看:107
本文介绍了在Clojure中搜索xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例xml:

 < data& 
< products>
< product>
< section>红色部分< / section>
< images>
< image> img.jpg< / image>
< image> img2.jpg< / image>
< / images>
< / product>
< product>
< section>蓝色部分< / section>
< images>
< image> img.jpg< / image>
< image> img3.jpg< / image>
< / images>
< / product>
< product>
< section>绿色部分< / section>
< images>
< image> img.jpg< / image>
< image> img2.jpg< / image>
< / images>
< / product>
< / products>
< / data>

我知道如何在Clojure中解析

 (需要'[clojure.xml:as xml])
(def x(xml / parse'location / of / that / xml'))


$ b 这返回一个描述xml的嵌套映射

  {:tag:data,
:attrs nil,
:content [
{:tag:products,
:attrs nil,
: content [
{:tag:product,
:attrs nil,
:content [] ..

这个结构当然可以用标准的Clojure函数遍历,但它可能会变得非常冗长,特别是如果与例如使用XPath查询它相比。有没有任何帮手来遍历和搜索这样的结构?我如何




  • 得到所有< product>

  • 只获取其< images> 标记包含< image> with textimg2.jpg

  • 获取部分为红色部分的产品



感谢

解决方案

a href =https://github.com/kyleburton/clj-xpath/ =nofollow> clj-xpath


I have the following sample 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>

I know how to parse it in Clojure

(require '[clojure.xml :as xml])
(def x (xml/parse 'location/of/that/xml'))

This returns a nested map describing the xml

{:tag :data,
 :attrs nil,
 :content [
     {:tag :products,
      :attrs nil,
      :content [
          {:tag :product,
           :attrs nil,
           :content [] ..

This structure can of course be traversed with standard Clojure functions, but it may turn out to be really verbose, especially if compared to, for instance, querying it with XPath. Is there any helper to traverse and search such structure? How can I, for example

  • get a list of all <product>
  • get only the product whose <images> tag contains an <image> with text "img2.jpg"
  • get the product whose section is "Red Section"

Thanks

解决方案

You can use a library like clj-xpath

这篇关于在Clojure中搜索xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆