2011-06-13 56 views

回答

5

试试这个:

user=> (use 'clojure.xml) 

user=> (for [x (xml-seq 
      (parse (java.io.File. file))) 
      :when (= :b (:tag x))] 
    (first (:content x))) 

检查这个link获取更多信息。

7

我不知道它是Clojure的怎么地道,但如果你碰巧知道和喜欢XPath可以用Clojure很容易由于使用其优良的interoperability with Java

(import javax.xml.parsers.DocumentBuilderFactory) 
(import javax.xml.xpath.XPathFactory) 

(defn document [filename] 
    (-> (DocumentBuilderFactory/newInstance) 
     .newDocumentBuilder 
     (.parse filename))) 

(defn get-value [document xpath] 
    (-> (XPathFactory/newInstance) 
     .newXPath 
     (.compile xpath) 
     (.evaluate document))) 

user=> (get-value (document "something.xml") "//a/b/text()") 
"SOMETHING" 
6

使用克里斯托夫大的伟大Enlive库:

(require '[net.cgrand.enlive-html :as html]) 

(map html/text 
    (html/select (html/html-snippet "<a><b>SOMETHING</b></a>") [:a :b])) 
10

拉链可以方便地用于xml,它们为您提供xpath,就像您可以与本地clojure函数混合使用的语法。

user=> (require '[clojure zip xml] '[clojure.contrib.zip-filter [xml :as x]]) 

user=> (def z (-> (.getBytes "<a><b>SOMETHING</b></a>") 
        java.io.ByteArrayInputStream. 
        clojure.xml/parse clojure.zip/xml-zip)) 

user=> (x/xml1-> z :b x/text) 

回报

"SOMETHING" 
+0

,因为它不仅功能更强大,也更容易,一旦你开窍了延长我建议这是最好的办法..所以+1拉链 – Ash 2011-08-30 17:10:50