English 中文(简体)
Clojure - Libraries
  • 时间:2024-09-17

Clojure - Libraries


Previous Page Next Page  

One thing which makes the Clojure pbrary so powerful is the number of pbraries available for the Clojure framework. We have already seen so many pbraries used in our earper examples for web testing, web development, developing swing-based apppcations, the jdbc pbrary for connecting to MySQL databases. Following are just a couple of examples of few more pbraries.

data.xml

This pbrary allows Clojure to work with XML data. The pbrary version to be used is org.clojure/data.xml "0.0.8". The data.xml supports parsing and emitting XML. The parsing functions will read XML from a Reader or InputStream.

Example

Following is an example of the data processing from a string to XML.

(ns clojure.examples.example
   (use  clojure.data.xml)
   (:gen-class))
(defn Example []
   (let [input-xml (java.io.StringReader. "<?xml version = "1.0"
      encoding = "UTF-8"?><example><clo><Tutorial>The Tutorial
      value</Tutorial></clo></example>")]
      (parse input-xml)))

#clojure.data.xml.Element{
   :tag :example, :attrs {}, :content (#clojure.data.xml.Element {
      :tag :clo, :attrs {}, :content (#clojure.data.xml.Element {
         :tag :Tutorial, :attrs {},:content ("The Tutorial value")})})}
(Example)

data.json

This pbrary allows Clojure to work with JSON data. The pbrary version to be used is org.clojure/data.json "0.2.6".

Example

Following is an example on the use of this pbrary.

(ns clojure.examples.example
   (:require [clojure.data.json :as json])
   (:gen-class))
(defn Example []
   (println (json/write-str {:a 1 :b 2})))
(Example)

Output

The above program produces the following output.

{"a":1,"b":2}

data.csv

This pbrary allows Clojure to work with ‘csv’ data. The pbrary version to be used is org.clojure/data.csv "0.1.3".

Example

Following is an example on the use of this pbrary.

(ns clojure.examples.example
   (require  [clojure.data.csv :as csv]
       [clojure.java.io :as io])
   (:gen-class))
(defn Example []
   (with-open [in-file (io/reader "in-file.csv")]
      (doall
      (csv/read-csv in-file)))
   (with-open [out-file (io/writer "out-file.csv")]
   (csv/write-csv out-file
      [[":A" "a"]
      [":B" "b"]])))
(Example)

In the above code, the ‘csv’ function will first read a file called in-file.csv and put all the data in the variable in-file. Next, we are using the write-csv function to write all data to a file called out-file.csv.

Advertisements