2014-03-01 39 views
4

XML可以原生Clojure的數據類型,並允許像爲什麼Clojure將xml文檔表示爲哈希映射?

(def myxml <inventors><clojure>Rich Hickey</clojure></inventors>) 

簡單的定義是什麼因素妨礙當前解析器從這樣

{:inventors {:clojure "Rich Hickey"}} 

,而不是這個

{:tag :inventors, :attrs nil, :content [{:tag :clojure, :attrs nil, :content ["Rich Hickey"]}]} 

的粗略搜索類似的表示在其他lisps我看到SXML 它支持命名空間。

+1

在'{:發明者{:clojure} Rich Hickey「}}',如果有的話,你會在哪裏放置價值? – leontalbot

+0

不知道@ user1184248命名空間和重複的節點名稱。 – KobbyPemson

回答

7

你們的榜樣尚不當你進入另一個發明者工作:

{:inventors 
    {:clojure "Rich Hickey"} 
    {:lisp "John McCarthy"}} 

(錯誤:這不是一個地圖)如果你把兩成一個子圖

,你不能有更多的比給定類型的一個孩子多。這很重要,因爲示例XML結構沒有正確設計。它應該是這樣的:

<inventors> 
    <inventor> 
    <language>Clojure</language> 
    <person>Rich Hickey</person> 
    </inventor> 
    <inventor> 
    <language>Lisp</language> 
    <person>John McCarthy</person> 
    </inventor> 
</inventors> 

你可以做的是使用列表或載體直接,而不是明確指定一個標籤的成分:

[:inventors {} 
    [:inventor {} 
    [:language {} "Clojure"] 
    [:person {} "Rich Hickey"]] 
    [:inventor {} 
    [:language {} "Lisp"] 
    [:person {} "John McCarthy"]]] 

看起來像這樣的常用使用的地圖結構:

{:tag :inventors 
:attrs nil 
:content [{:tag :inventor 
      :attrs nil 
      :content [{:tag :language 
         :attrs nil 
         :content "Clojure"} 
         {:tag :person 
         :attrs nil 
         :content "Rich Hickey"}]} 
      {:tag :inventor 
      :attrs nil 
      :content [{:tag :language 
         :attrs nil 
         :content "Lisp"} 
         {:tag :person 
         :attrs nil 
         :content "John McCarthy"}]}]} 

這可能類似於上面的向量的建議是清潔的,但你必須定義訪問功能(理智)與載體的工作。這些地圖在Clojure中已經是它們自己的訪問器函數,所以你可以直接和慣用地使用它們。

+0

你說得對xml沒有正確設計,但不幸的是,這是有效的XML和應用程序,我想與生產或消費xmls一樣。 – KobbyPemson

+0

@KobbyPemson:我很可惜,但這對於手頭的問題並不相關,因爲您不想設計只能表示XML文檔的一小部分的XML表示,對嗎? :) – Svante

+0

好點,但你不得不承認當前的表示比XML更不可讀,並且任何表示都應該允許在任何有效的xml上進行無損循環跳轉。 – KobbyPemson

5

替代方括號的捲曲的和你在說什麼是hiccup格式。

user=> (hiccup.core/html [:inventors [:clojure "Rich Hickey"]]) 
"<inventors><clojure>Rich Hickey</clojure></inventors>" 

您可以使用打嗝式樣與data.xml

+0

難道不是這樣嗎? (xml - >哈希映射)。 – leontalbot