为什么Clojure将xml文档表示为哈希映射?

Kob*_*son 4 lisp xml xslt clojure

xml可以是本机clojure数据类型,并允许简单的定义,如

(def myxml <inventors><clojure>Rich Hickey</clojure></inventors>)
Run Code Online (Sandbox Code Playgroud)

是什么阻止了当前的解析器这样做

{:inventors {:clojure "Rich Hickey"}}
Run Code Online (Sandbox Code Playgroud)

而不是这个

{:tag :inventors, :attrs nil, :content [{:tag :clojure, :attrs nil, :content ["Rich Hickey"]}]}
Run Code Online (Sandbox Code Playgroud)

粗略搜索其他lisps中的类似表示我看到 支持命名空间的SXML.

Sva*_*nte 7

当您输入另一个发明人时,您的示例不起作用:

{:inventors
  {:clojure "Rich Hickey"}
  {:lisp "John McCarthy"}}
Run Code Online (Sandbox Code Playgroud)

(错误:那不是地图.)

如果将两者都放在一个子图中,则不能有多个给定类型的子项.这很重要,因为没有正确设计示例XML结构.它应该是这样的:

<inventors>
  <inventor>
    <language>Clojure</language>
    <person>Rich Hickey</person>
  </inventor>
  <inventor>
    <language>Lisp</language>
    <person>John McCarthy</person>
  </inventor>
</inventors>
Run Code Online (Sandbox Code Playgroud)

您可以做的是直接使用列表或向量,而不是显式命名单个标记的组件:

[:inventors {}
  [:inventor {}
    [:language {} "Clojure"]
    [:person {} "Rich Hickey"]]
  [:inventor {}
    [:language {} "Lisp"]
    [:person {} "John McCarthy"]]]
Run Code Online (Sandbox Code Playgroud)

在常用的地图结构中看起来像这样:

{: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"}]}]}
Run Code Online (Sandbox Code Playgroud)

这可能看起来像上面的向量提议更清晰,但您必须定义访问器函数(明智地)使用这些向量.这些地图在Clojure中已经是它们自己的访问器功能,因此您可以直接和惯用地使用它们.


A. *_*ebb 5

用卷曲替换方形括号,你所说的是打嗝格式.

user=> (hiccup.core/html [:inventors [:clojure "Rich Hickey"]])
"<inventors><clojure>Rich Hickey</clojure></inventors>"
Run Code Online (Sandbox Code Playgroud)

您可以在data.xml中使用类似打嗝的样式.