使用 org.clojure/data.xml 生成 XML 时在最新的稳定版本 0.0.8 中,我们得到了一个非命名空间的 XML。在使用最新预览版 0.2.0-alpha6 生成 XML 时,它会生成带前缀的 XML。
根据libraries documentation , namespace 支持是一项新功能。但是,如何生成没有命名空间的 XML?对于某些 XML,例如 Atom,这是对有效 XML 的要求。
这是适用于两个版本的代码:
(xml/emit-str
(xml/sexp-as-element
[:feed {:xmlns "http://www.w3.org/2005/Atom"}]))
在稳定版中,它会生成:
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><feed xmlns=\"http://www.w3.org/2005/Atom\"/>"
在预览版中,它生成:
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><feed xmlns:a=\"http://www.w3.org/2005/Atom\"/>"
注意后者自动生成的 :a
命名空间前缀。
更新:alex-miller在https://stackoverflow.com/a/64615916/252585中提出了上述问题的解决方案
我非常愿意接受这个答案,因为它似乎解决了我的问题。但是,为了获得有效的 Atom 提要,它将问题推向了更深的层次。我查看了包含有关使用 URI 别名的新信息的文档,但未能成功生成别名。这是所提出的方法产生的新问题:
clojure.data.xml 的稳定版本产生:
(xml/emit-str
(xml/sexp-as-element
[:feed {:xmlns "http://www.w3.org/2005/Atom"}
[:title "Some site title"]]))
=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?><feed xmlns:a=\"http://www.w3.org/2005/Atom\"><title>Some site title</title></feed>"
采用新方法的最新版本产生:
(xml/emit-str
(xml/sexp-as-element
[::atom/feed {:xmlns "http://www.w3.org/2005/Atom"}
[:title "Some site title"]]))
=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?><feed xmlns=\"http://www.w3.org/2005/Atom\"><title xmlns=\"\" xmlns:a=\"http://www.w3.org/2005/Atom\">Some site title</title></feed>"
此语法将再次被 Atom 验证器和提要阅读器拒绝。这是一个例子:https://user-images.githubusercontent.com/505721/97803188-bbdd5600-1c48-11eb-986a-14d441344e70.png
最佳答案
我认为你可以使用 uri 别名得到你想要的东西:
(require '[clojure.data.xml :as xml])
;; declare a uri alias in this namespace
(xml/alias-uri 'atom "http://www.w3.org/2005/Atom")
;; use the alias as tag prefix, but also declare at the root as default
(xml/emit-str
(xml/sexp-as-element
[::atom/feed {:xmlns "http://www.w3.org/2005/Atom"}]))
;; emitted string:
;; "<?xml version=\"1.0\" encoding=\"UTF-8\"?><feed xmlns=\"http://www.w3.org/2005/Atom\"/>"
关于xml - 如何使用最新版本的 org.clojure/data.xml 生成没有命名空间的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64611482/