Clojure XML Parsing

后端 未结 2 2045
忘了有多久
忘了有多久 2020-12-22 16:40

I can not find any info on how to parse xml documents and access elements.

I have found two ways to parse the xml document

(clojure.zip/xml-zip (cloj         


        
2条回答
  •  一生所求
    2020-12-22 17:47

    The above answer works, but I find it a lot easier to use clojure.data.zip.xml (used to be clojure-contrib.zip-filter.xml prior to Clojure 1.3).

    file:

    myfile.xml:

    
      Track one
      Track two
    
    

    code:

    ; Clojure 1.3
    (ns example
      (:use [clojure.data.zip.xml :only (attr text xml->)]) ; dep: see below
      (:require [clojure.xml :as xml]
                [clojure.zip :as zip]))
    
    (def xml (xml/parse "myfile.xml"))
    (def zipped (zip/xml-zip xml))
    (xml-> zipped :track :name text)       ; ("Track one" "Track two")
    (xml-> zipped :track (attr :id))       ; ("t1" "t2")
    

    Unfortunately, you need to pull in a dependency on data.zip to get this nice read/filter functionality. It's worth the dependency :) In lein it would be (as of 17-Aug-2013):

    [org.clojure/data.zip "0.1.1"]
    

    And as for docs for data.zip.xml ... I just look at the relatively small source file here to see what is possible. Another good SO answer here, too.

提交回复
热议问题