首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用clojure xml zipper返回多个值

使用clojure xml zipper返回多个值
EN

Stack Overflow用户
提问于 2010-01-10 03:04:33
回答 2查看 1.1K关注 0票数 4

假设我们有一些如下的XML:

代码语言:javascript
复制
<a>
  <b>
    <c>text</c>
    <d>
      <e>text</e>
      <f>
        ... lots of cruft here ..
      </f>
    </d>
  </b>
  <b>
    ...
  </b>
  <!-- more b sub-trees --> 
</a>

现在,查看zip_filter/xml.clj中的示例,我已经找到了如何获得我感兴趣的单个值。

我想知道如何做一些事情,比如返回成对的文本值(c,e)。

编辑:

这里有一些可以工作的代码,但它相当难看。不要求琐碎的重构,但是拉链有没有更好的方式让我们做到这一点呢?

代码语言:javascript
复制
(defn extract-data [xml] 
  (let [items (x/xml-> xml zf/descendants :Item)     ;items not top-level
        getAttributes  #(x/xml1-> % :ItemAttributes) ;items have itemattributes
        getASIN        #(x/xml1-> % :ASIN x/text)    ;items have ASINs
        getTitle       #(x/xml1-> % :Title x/text)   ;itemattributes have Titles
        getAuthor      #(x/xml1-> % :Author x/text)] ;itemattributes have Authors
    (map 
       ;build a function to get everything we need from the items, and apply
      #(let [attributes (getAttributes %)] ;get the attributes, we'll use it twice
         (list 
           (getASIN %) 
           (getTitle attributes) 
           (getAuthor attributes)))
      items)))
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-01-11 20:34:19

根据您使用的clojure版本,您可能会发现juxt函数很有用。您发布的代码(仅限相关部分):

代码语言:javascript
复制
(defn extract-data
  [xml] 
  (let [...]
    (map (juxt getASIN (comp getTitle getAttributes) (comp getAuthor getAttributes)) items))))
票数 4
EN

Stack Overflow用户

发布于 2010-01-11 12:26:32

我相信有一种更好的方法,但这样做是可行的:

代码语言:javascript
复制
(letfn [(get-tag [tag coll] (:content (first (filter #(= tag (:tag %)) coll))))]
  (map #(list (get-tag :c %) (get-tag :e (get-tag :d %)))
       (map :content (:content (clojure.xml/parse "foo.xml")))))

结果:

代码语言:javascript
复制
((["ctext1"] ["etext1"]) (["ctext2"] ["etext2"]))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2034550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档