在Clojure中获取XML中元素的值?

Zub*_*air 7 xml clojure

在Clojure中从XML字符串中获取元素值的最简单方法是什么?我正在寻找类似的东西:

(get-value "<a><b>SOMETHING</b></a>)" "b")
Run Code Online (Sandbox Code Playgroud)

回来

"SOMETHING"
Run Code Online (Sandbox Code Playgroud)

use*_*049 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)
Run Code Online (Sandbox Code Playgroud)

回报

"SOMETHING"
Run Code Online (Sandbox Code Playgroud)


Jon*_*nas 7

我不知道它是如何惯用的Clojure但是如果你碰巧知道并喜欢XPath,它可以很容易地在Clojure中使用,因为它与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"
Run Code Online (Sandbox Code Playgroud)


Jür*_*zel 6

使用Christophe Grand的伟大Enlive图书馆:

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

(map html/text
     (html/select (html/html-snippet "<a><b>SOMETHING</b></a>")  [:a :b]))
Run Code Online (Sandbox Code Playgroud)


Has*_*him 5

试试这个:

user=> (use 'clojure.xml)

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

请查看此链接以获取更多信息.