【问题标题】:returning multiple values using clojure xml zipper使用 clojure xml 拉链返回多个值
【发布时间】:2011-01-03 07:43:33
【问题描述】:

假设我们有一些这样的 XML:

<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) 的文本值对列表。

编辑:

这是一些工作代码,但它非常难看。不要求进行微不足道的重构,但是拉链给我们提供了更好的方法来做到这一点吗?

(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)))

【问题讨论】:

    标签: xml clojure zipper


    【解决方案1】:

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

    (defn extract-data
      [xml] 
      (let [...]
        (map (juxt getASIN (comp getTitle getAttributes) (comp getAuthor getAttributes)) items))))
    

    【讨论】:

    • +1 向我展示了并列和更简洁的布局方式。很快就会试用。
    • 酷。我也可以这样做以避免 2 次调用 getAttributes。 (map (juxt getASIN (comp (juxt getTitle getAuthor) getAttributes)) items) 但我必须将向量展平。
    【解决方案2】:

    我确信有更好的方法,但这确实有效:

    (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")))))
    

    结果

    ((["ctext1"] ["etext1"]) (["ctext2"] ["etext2"]))
    

    【讨论】:

    • 谢谢,我刚刚发布了一些我正在使用的真实数据结构的实际代码。 +1 向我展示了 letfn 和这样做的一种方法。
    猜你喜欢
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多