xml - 如何使用最新版本的 org.clojure/data.xml 生成没有命名空间的 XML

标签 xml clojure

使用 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/

相关文章:

xml - libxml2 复制没有命名空间的节点或替换/删除命名空间

clojure - Compojure - 使用重定向时避免 "manual"URL 格式

XmlPullParser - 如何跳到匹配的END_TAG?

xml - 如何在 Linux 中格式化 XML 文档

java - 在 Main 方法中使用 XML 派生变量

Emacs htmlize 在批处理模式下?

用于封装的 Clojure 对象和高阶函数

java - 使用迭代时超出 Clojure GC 开销限制

clojure.tools.namespace.repl/refresh 不起作用

javacode/Id 中的 java android 空间