### Install clojure.data.xml Source: https://context7.com/clojure/data.xml/llms.txt Add the clojure.data.xml library to your project dependencies using either deps.edn or Leiningen. Stable and preview versions are available. ```clojure ;; deps.edn (stable) org.clojure/data.xml {:mvn/version "0.0.8"} ;; deps.edn (preview – namespace + ClojureScript support) org.clojure/data.xml {:mvn/version "0.2.0-alpha11"} ;; Leiningen (stable) [org.clojure/data.xml "0.0.8"] ;; Leiningen (preview) [org.clojure/data.xml "0.2.0-alpha11"] ``` -------------------------------- ### Namespace Prefix Equality Check Source: https://github.com/clojure/data.xml/blob/master/README.md Illustrates that JDK QName ignores namespace prefixes for equality checks but preserves them for emitting. This example compares two parsed strings with different prefixes but the same namespace URI. ```clojure (= (xml/parse-str "Example title") (xml/parse-str "Example title")) ``` -------------------------------- ### Get Namespace Environment with `element-nss` Source: https://context7.com/clojure/data.xml/llms.txt Retrieves the prefix-to-URI mapping in effect at a given XML element. Merges explicit `:xmlns/*` attributes with parser-populated metadata. ```clojure (require '[clojure.data.xml :as xml] '[clojure.data.xml.event :as event]) ;; Namespace environment preserved through a round-trip (def parsed (xml/parse-str "")) (event/element-nss parsed) ;; => {"foo" "FOO:"} (prefix-uri map) ``` ```clojure ;; Metadata namespace map (populated by the parser) (-> parsed meta :clojure.data.xml/nss) ``` ```clojure ;; Prefix info is used when re-emitting to preserve original prefixes (xml/emit-str (xml/parse-str "")) ;; => "" ``` -------------------------------- ### Customize Namespace Prefixes with xmlns Attribute Source: https://github.com/clojure/data.xml/blob/master/README.md Customizes namespace prefixes by explicitly declaring them as attributes in the 'xmlns' kw-namespace. This example uses 'foo' as the prefix. ```clojure (xml/emit-str (xml/element (xml/qname "http://www.w3.org/1999/xhtml" "title") {:xmlns/foo "http://www.w3.org/1999/xhtml"} "Example title")) ``` ```xml " Example title" ``` -------------------------------- ### Serialize XML Element Tree to String with clojure.data.xml Source: https://context7.com/clojure/data.xml/llms.txt Use `emit-str` to get the XML representation of an element tree as a `String`. It accepts `:encoding` and `:doctype` options, similar to `emit`. Useful for testing and debugging. ```clojure (require '[clojure.data.xml :as xml]) (xml/emit-str (xml/element :foo {:foo-attr "foo value"} (xml/element :bar {:bar-attr "bar value"} (xml/element :baz {} "The baz value")))) ``` ```clojure ;; Verify round-trip fidelity (let [tree (xml/element :root {:version "1"} (xml/element :child {} "data"))] (= tree (xml/parse-str (xml/emit-str tree)))) ``` ```clojure ;; Various Clojure types are auto-serialized to XML strings (xml/emit-str (xml/element :data {} true ;; "true" 42 ;; "42" 3/4 ;; "0.75" (java.util.Date. 0))) ;; "1970-01-01T00:00:00.000-00:00") ``` -------------------------------- ### Clojure CLI/deps.edn Dependency (Preview) Source: https://github.com/clojure/data.xml/blob/master/README.md Add this to your deps.edn file for the preview version of data.xml. ```clojure org.clojure/data.xml {:mvn/version "0.2.0-alpha11"} ``` -------------------------------- ### Create XML Comment and Element in Clojure Source: https://github.com/clojure/data.xml/blob/master/README.md Demonstrates how to create an XML comment and an element using the xml/xml-comment and xml/element functions. The output shows the resulting XML string. ```clojure (xml/xml-comment "Just a goes here") (xml/element :bar {} "and another element"))))) ``` ```xml and another element ``` -------------------------------- ### Create XML with CDATA using sexp-as-element Source: https://github.com/clojure/data.xml/blob/master/README.md Demonstrates creating an XML element with a CDATA section using the sexp-as-element function. The CDATA content is specified using the :-cdata tag. ```clojure (= (xml/element :tag {:attr "value"} (xml/element :body {} (xml/cdata "not parsed true ``` -------------------------------- ### Emit Namespaced Tags using QName and String Encoding Source: https://github.com/clojure/data.xml/blob/master/README.md Demonstrates emitting namespaced tags using 'xml/qname' for Java QName instances or directly with the '{ns}n' string encoding. ```clojure (xml/emit-str {:tag (xml/qname "http://www.w3.org/1999/xhtml" "html")}) ``` ```clojure (xml/emit-str {:tag "{http://www.w3.org/1999/xhtml}html"}) ``` ```xml " " ``` -------------------------------- ### Leiningen Dependency for data.xml (Preview) Source: https://github.com/clojure/data.xml/blob/master/README.md Add this to your project.clj dependencies for the preview version of data.xml. ```clojure [org.clojure/data.xml "0.2.0-alpha11"] ``` -------------------------------- ### Compare XML elements created with element and sexp-as-element Source: https://github.com/clojure/data.xml/blob/master/README.md Compares XML structures created using the xml/element function and the Hiccup-like sexp-as-element syntax. Both should produce equivalent XML structures. ```clojure (= (xml/element :foo {:foo-attr "foo value"} (xml/element :bar {:bar-attr "bar value"} (xml/element :baz {} "The baz value"))) (xml/sexp-as-element [:foo {:foo-attr "foo value"} [:bar {:bar-attr "bar value"} [:baz {} "The baz value"]]])) ;;-> true ``` -------------------------------- ### Maven Dependency for data.xml (Preview) Source: https://github.com/clojure/data.xml/blob/master/README.md Add this to your pom.xml's section for the preview version of data.xml. ```xml org.clojure data.xml 0.2.0-alpha11 ``` -------------------------------- ### Clojure CLI/deps.edn Dependency (Stable) Source: https://github.com/clojure/data.xml/blob/master/README.md Add this to your deps.edn file for the stable version of data.xml. ```clojure org.clojure/data.xml {:mvn/version "0.0.8"} ``` -------------------------------- ### qname / parse-qname / qname-uri / qname-local Source: https://context7.com/clojure/data.xml/llms.txt Utilities for working with qualified names (QNames). `qname` constructs a namespaced keyword, `parse-qname` parses Clark notation strings, and `qname-uri`/`qname-local` extract parts of a QName. ```APIDOC ## `qname` / `parse-qname` / `qname-uri` / `qname-local` — Qualified name utilities `qname` constructs a namespaced keyword from a URI and local name. `parse-qname` parses the `{uri}local` Clark notation string into a keyword. `qname-uri` and `qname-local` extract the namespace URI and local part from any QName representation (keyword, `javax.xml.namespace.QName`, or `{ns}local` string). ### Usage ```clojure (require '[clojure.data.xml :as xml]) ;; Build a QName keyword (xml/qname "http://www.w3.org/1999/xhtml" "div") ;; => :xmlns.http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml/div ;; Parse Clark notation (xml/parse-qname "{http://www.w3.org/1999/xhtml}div") ;; => :xmlns.http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml/div ;; Extract parts (xml/qname-uri :xmlns.http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml/div) ;; => "http://www.w3.org/1999/xhtml" (xml/qname-local :xmlns.http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml/div) ;; => "div" ;; javax.xml.namespace.QName instances are supported (xml/emit-str {:tag (xml/qname "http://www.w3.org/1999/xhtml" "html")}) ;; => "" ;; String Clark notation is also accepted as :tag (xml/emit-str {:tag "{http://www.w3.org/1999/xhtml}html"}) ;; => "" ``` ``` -------------------------------- ### Alias URI for Namespaced XML Emission Source: https://github.com/clojure/data.xml/blob/master/README.md Demonstrates aliasing a URI to a keyword prefix for emitting namespaced XML elements. Ensure 'alias-uri' is defined at the top level. ```clojure (xml/alias-uri 'xh "http://www.w3.org/1999/xhtml") ``` ```clojure (xml/emit-str {:tag ::xh/html :content [{:tag ::xh/head} {:tag ::xh/body :content ["DOCUMENT"]}]}) ``` ```xml DOCUMENT ``` -------------------------------- ### Round trip XML parsing and emitting Source: https://github.com/clojure/data.xml/blob/master/README.md Emits XML to a file and then parses it back, demonstrating the library's ability to 'round trip' XML data. This verifies that the emitted XML can be correctly parsed. ```clojure (let [tags (xml/element :foo {:foo-attr "foo value"} (xml/element :bar {:bar-attr "bar value"} (xml/element :baz {} "The baz value")))] (with-open [out-file (java.io.FileWriter. "/tmp/foo.xml")] (xml/emit tags out-file)) (with-open [input (java.io.FileInputStream. "/tmp/foo.xml")] (xml/parse input))) #xml/element{:tag :foo, :attrs {:foo-attr "foo value"}...} ``` -------------------------------- ### Qualified Name Utilities: `qname`, `parse-qname`, `qname-uri`, `qname-local` Source: https://context7.com/clojure/data.xml/llms.txt Utilities for constructing and deconstructing qualified names (QNames). Supports keyword, Clark notation, and `javax.xml.namespace.QName`. ```clojure (require '[clojure.data.xml :as xml]) ;; Build a QName keyword (xml/qname "http://www.w3.org/1999/xhtml" "div") ;; => :xmlns.http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml/div ``` ```clojure ;; Parse Clark notation (xml/parse-qname "{http://www.w3.org/1999/xhtml}div") ;; => :xmlns.http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml/div ``` ```clojure ;; Extract parts (xml/qname-uri :xmlns.http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml/div) ;; => "http://www.w3.org/1999/xhtml" ``` ```clojure (xml/qname-local :xmlns.http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml/div) ;; => "div" ``` ```clojure ;; javax.xml.namespace.QName instances are supported (xml/emit-str {:tag (xml/qname "http://www.w3.org/1999/xhtml" "html")}) ;; => "" ``` ```clojure ;; String Clark notation is also accepted as :tag (xml/emit-str {:tag "{http://www.w3.org/1999/xhtml}html"}) ;; => "" ``` -------------------------------- ### Create and emit XML elements to a Writer Source: https://github.com/clojure/data.xml/blob/master/README.md Creates XML elements using nested element functions and emits them to a java.io.FileWriter. Ensure the file path is writable. ```clojure (let [tags (xml/element :foo {:foo-attr "foo value"} (xml/element :bar {:bar-attr "bar value"} (xml/element :baz {} "The baz value")))] (with-open [out-file (java.io.FileWriter. "/tmp/foo.xml")] (xml/emit tags out-file))) ``` -------------------------------- ### Create XML element with element function Source: https://context7.com/clojure/data.xml/llms.txt Use the `element` function to construct XML elements. It accepts a tag keyword, optional attributes map, and child nodes. Plain maps with :tag, :attrs, and :content keys are also accepted. ```clojure (require '[clojure.data.xml :as xml]) ;; Simple element with no attributes or content (xml/element :item) ;; => #xml/element{:tag :item} ;; Element with attributes and text content (xml/element :title {:lang "en"} "Hello World") ;; => #xml/element{:tag :title, :attrs {:lang "en"}, :content ["Hello World"]} ;; Nested element tree (xml/element :catalog {} (xml/element :book {:id "bk101"} (xml/element :author {} "Gambardella, Matthew") (xml/element :title {} "XML Developer's Guide") (xml/element :price {} "44.95"))) ;; => #xml/element{:tag :catalog, :attrs {}, :content [#xml/element{...}]} ;; Plain-map form works too {:tag :note :attrs {:type "info"} :content ["text"]} ``` -------------------------------- ### Define Namespace Aliases with `alias-uri` Source: https://context7.com/clojure/data.xml/llms.txt Registers Clojure namespace aliases for concise `::alias/keyword` syntax. Must be called at the top level of a namespace. ```clojure (require '[clojure.data.xml :as xml]) ;; Declare aliases at namespace top level (xml/alias-uri 'xhtml "http://www.w3.org/1999/xhtml" 'D "DAV:" 'atom "http://www.w3.org/2005/Atom") ``` ```clojure ;; Use ::alias/local keywords to build namespaced elements (xml/emit-str (xml/element ::xhtml/html {} (xml/element ::xhtml/head {} (xml/element ::xhtml/title {} "My Page")) (xml/element ::xhtml/body {} (xml/element ::xhtml/p {} "Hello, world!")))) ;; => " ;; ;; My Page ;; Hello, world! ;; " ``` ```clojure ;; Emit with explicit default namespace (no prefix) (xml/emit-str (xml/element ::xhtml/html {:xmlns "http://www.w3.org/1999/xhtml"} (xml/element ::xhtml/body {} "DOCUMENT"))) ;; => "....DOCUMENT" ``` ```clojure ;; Parse namespaced XML – aliases allow clean keyword access (xml/alias-uri 'D "DAV:") (= (xml/element ::D/limit {} (xml/element ::D/nresults nil "100")) (xml/parse-str "100")) ;; => true ``` -------------------------------- ### Pretty-print XML with Indentation using clojure.data.xml Source: https://context7.com/clojure/data.xml/llms.txt Use `indent-str` to re-emit XML with indentation for human readability, or `indent` to write indented output directly to a Writer. These functions are intended for debugging and development due to performance. ```clojure (require '[clojure.data.xml :as xml]) (print (xml/indent-str (xml/element :catalog {} (xml/element :book {:id "bk101"} (xml/element :title {} "XML Developer's Guide") (xml/element :price {} "44.95"))))) ``` ```clojure ;; Write indented output directly to a Writer (with-open [out (clojure.java.io/writer "pretty.xml")] (xml/indent (xml/element :root {} (xml/element :child {} "value")) out)) ``` -------------------------------- ### Emit Parsed XML with Retained Namespace Prefixes Source: https://github.com/clojure/data.xml/blob/master/README.md Emits XML parsed from a string, retaining the original namespace prefix ('foo' in this case) if metadata is present. If no metadata exists, new prefixes will be generated. ```clojure (xml/emit-str (xml/parse-str "")) ``` -------------------------------- ### Leiningen Dependency for data.xml (Stable) Source: https://github.com/clojure/data.xml/blob/master/README.md Add this to your project.clj dependencies for the stable version of data.xml. ```clojure [org.clojure/data.xml "0.0.8"] ``` -------------------------------- ### Maven Dependency for data.xml (Stable) Source: https://github.com/clojure/data.xml/blob/master/README.md Add this to your pom.xml's section for the stable version of data.xml. ```xml org.clojure data.xml 0.0.8 ``` -------------------------------- ### element — Create an XML element node Source: https://context7.com/clojure/data.xml/llms.txt Constructs an Element record from a tag keyword, an optional attribute map, and zero or more child nodes. Plain maps with :tag, :attrs, and :content keys are also accepted. ```APIDOC ## `element` — Create an XML element node ### Description Constructs an `Element` record from a tag keyword, an optional attribute map, and zero or more child nodes (strings or nested elements). Plain maps with `:tag`, `:attrs`, and `:content` keys are also accepted everywhere an element is expected. ### Usage ```clojure (require '[clojure.data.xml :as xml]) ;; Simple element with no attributes or content (xml/element :item) ;; => #xml/element{:tag :item} ;; Element with attributes and text content (xml/element :title {:lang "en"} "Hello World") ;; => #xml/element{:tag :title, :attrs {:lang "en"}, :content ["Hello World"]} ;; Nested element tree (xml/element :catalog {} (xml/element :book {:id "bk101"} (xml/element :author {} "Gambardella, Matthew") (xml/element :title {} "XML Developer's Guide") (xml/element :price {} "44.95"))) ;; => #xml/element{:tag :catalog, :attrs {}, :content [#xml/element{...}]} ;; Plain-map form works too {:tag :note :attrs {:type "info"} :content ["text"]} ``` ``` -------------------------------- ### Parse XML with Namespaces Source: https://github.com/clojure/data.xml/blob/master/README.md Parses an XHTML document and shows the resulting XML element representation with namespaced tags encoded as Clojure keywords. ```clojure (xml/parse-str " ") ``` ```clojure #xml/element{:tag :xmlns.http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml/html} ``` -------------------------------- ### Create and Emit CDATA Section Source: https://context7.com/clojure/data.xml/llms.txt Wraps a string in a CDATA section. CDATA sections with embedded ']]>' are automatically split. Parsed CDATA content is returned as a plain string. ```clojure (require '[clojure.data.xml :as xml]) ;; Embed raw markup-like content without escaping (xml/emit-str (xml/element :script {} (xml/cdata "if (x < 10 && y > 0) { return ''; }"))) ;; => "" ;; CDATA with embedded ]]> is automatically split (xml/emit-str (xml/element :data {} (xml/cdata "end]]>here"))) ;; => "....here]]>" ;; Parsed back as plain text (CDATA is transparent to the reader) (xml/parse-str (xml/emit-str (xml/element :foo {} (xml/cdata "&data")))) ;; => #xml/element{:tag :foo, :content ["&data"]} ``` -------------------------------- ### Emit Namespaced XML with Default xmlns Source: https://github.com/clojure/data.xml/blob/master/README.md Emits namespaced XML without prefixes by setting the default xmlns at the root element. URIs must match. ```clojure (xml/alias-uri 'xh "http://www.w3.org/1999/xhtml") ``` ```clojure (xml/emit-str (xml/element ::xh/html {:xmlns "http://www.w3.org/1999/xhtml"} (xml/element ::xh/head) (xml/element ::xh/body {} "DOCUMENT"))) ``` ```xml " DOCUMENT " ``` -------------------------------- ### Require clojure.data.xml namespace Source: https://context7.com/clojure/data.xml/llms.txt Import the clojure.data.xml library into your Clojure project to use its functions. ```clojure (require '[clojure.data.xml :as xml]) ``` -------------------------------- ### Emit Namespaced XML using Hiccup Style Source: https://github.com/clojure/data.xml/blob/master/README.md Emits namespaced XML using a concise hiccup-style syntax, achieving the same output as the element-based approach. ```clojure (xml/alias-uri 'xh "http://www.w3.org/1999/xhtml") ``` ```clojure (xml/emit-str (xml/sexp-as-element [::xh/html {:xmlns "http://www.w3.org/1999/xhtml"} [::xh/head] [::xh/body "DOCUMENT"]])) ``` -------------------------------- ### Namespace Aggregation with `find-xmlns` and `aggregate-xmlns` Source: https://context7.com/clojure/data.xml/llms.txt Utilities to find all namespace URIs in an element tree and aggregate them onto the root element for a single top-level namespace declaration block. ```clojure (require '[clojure.data.xml :as xml] '[clojure.data.xml.process :as process]) (xml/alias-uri 'xhtml "http://www.w3.org/1999/xhtml" 'D "DAV:") (def my-doc (xml/element ::xhtml/html {} (xml/element ::xhtml/body {} (xml/element ::D/propfind {})))) ``` ```clojure ;; Find all namespace URIs used in the tree (process/find-xmlns my-doc) ;; => #{"http://www.w3.org/1999/xhtml" "DAV:"} ``` ```clojure ;; Aggregate all namespace declarations to the root element (def doc-with-ns (process/aggregate-xmlns my-doc)) (xml/emit-str doc-with-ns) ;; All xmlns: declarations appear on the root element ``` -------------------------------- ### Indent XML string for debugging Source: https://github.com/clojure/data.xml/blob/master/README.md Uses xml/indent-str to pretty-print an XML structure to a string. This is primarily for debugging and may be slow for large XML documents. ```clojure (print (xml/indent-str (xml/element :foo {:foo-attr "foo value"} (xml/element :bar {:bar-attr "bar value"} (xml/element :baz {} "The baz value1") (xml/element :baz {} "The baz value2") (xml/element :baz {} "The baz value3"))))) The baz value1 The baz value2 The baz value3 ``` -------------------------------- ### Emit XML Element Tree to Writer with clojure.data.xml Source: https://context7.com/clojure/data.xml/llms.txt Use `emit` to serialize an element tree to a `java.io.Writer` or `java.io.OutputStream`. It writes a standard XML declaration header and supports specifying encoding and DOCTYPE. ```clojure (require '[clojure.data.xml :as xml] '[clojure.java.io :as io]) ;; Write to a file (let [doc (xml/element :catalog {} (xml/element :book {:id "1"} "Clojure Programming"))] (with-open [out (io/writer "output.xml")] (xml/emit doc out))) ``` ```clojure ;; Specify encoding (let [doc (xml/element :greeting {} "Übercool")] (with-open [out (io/output-stream "output.xml")] (xml/emit doc (java.io.OutputStreamWriter. out "ISO-8859-1") :encoding "ISO-8859-1"))) ``` ```clojure ;; Emit with a DOCTYPE declaration (let [doc (xml/element :html {} (xml/element :body {} "Hello"))] (with-open [out (io/writer "page.html")] (xml/emit doc out :doctype ""))) ``` -------------------------------- ### alias-uri Source: https://context7.com/clojure/data.xml/llms.txt Registers Clojure namespace aliases for use with the `::alias/keyword` syntax. This function must be called at the top level of a namespace to allow the reader to expand shortcuts during compilation. ```APIDOC ## `alias-uri` — Define namespace aliases for use with `::alias/keyword` syntax Registers a Clojure namespace alias mapping a short symbol to an XML namespace URI, enabling the concise `::alias/local-name` keyword reader syntax for namespaced QNames. Must be called at the top level of the namespace (not inside a function) so the reader can expand the `::` shortcuts during compilation. ### Usage ```clojure (require '[clojure.data.xml :as xml]) ;; Declare aliases at namespace top level (xml/alias-uri 'xhtml "http://www.w3.org/1999/xhtml" 'D "DAV:" 'atom "http://www.w3.org/2005/Atom") ;; Use ::alias/local keywords to build namespaced elements (xml/emit-str (xml/element ::xhtml/html {} (xml/element ::xhtml/head {} (xml/element ::xhtml/title {} "My Page")) (xml/element ::xhtml/body {} (xml/element ::xhtml/p {} "Hello, world!")))) ;; => " ;; ;; My Page ;; Hello, world! ;; " ;; Emit with explicit default namespace (no prefix) (xml/emit-str (xml/element ::xhtml/html {:xmlns "http://www.w3.org/1999/xhtml"} (xml/element ::xhtml/body {} "DOCUMENT"))) ;; => "....DOCUMENT" ;; Parse namespaced XML – aliases allow clean keyword access (xml/alias-uri 'D "DAV:") (= (xml/element ::D/limit {} (xml/element ::D/nresults nil "100")) (xml/parse-str "100")) ;; => true ``` ``` -------------------------------- ### Compare parsed string with emitted string Source: https://github.com/clojure/data.xml/blob/master/README.md Compares an XML structure with its string representation after emitting and then parsing it back. This tests the consistency of string-based parsing and emitting. ```clojure (let [tags (xml/element :foo {:foo-attr "foo value"} (xml/element :bar {:bar-attr "bar value"} (xml/element :baz {} "The baz value")))] (= tags (xml/parse-str (xml/emit-str tags)))) true ``` -------------------------------- ### Lazy Pull-Parsing Event Sequence Source: https://context7.com/clojure/data.xml/llms.txt Returns a lazy sequence of pull-parse events from an InputStream or Reader for memory-efficient processing of large XML files. Can be passed to 'emit'/'emit-str' for stream-to-stream transformation. ```clojure (require '[clojure.data.xml :as xml]) ;; Inspect raw events (xml/event-seq (java.io.StringReader. "12") {}) ;; => (#StartElementEvent{:tag :root ...} ;; #StartElementEvent{:tag :item ...} ;; #CharsEvent{:str "1"} ;; #EndElementEvent{:tag :item ...} ;; #StartElementEvent{:tag :item ...} ;; #CharsEvent{:str "2"} ;; #EndElementEvent{:tag :item ...} ;; #EndElementEvent{:tag :root ...}) ;; Stream transformation: parse → filter → re-emit (no full tree in memory) (let [events (xml/event-seq (java.io.FileInputStream. "large.xml") {})] (xml/emit-str events)) ;; Include comment events (xml/event-seq (java.io.StringReader. "") {:include-node? #{:element :characters :comment}}) ``` -------------------------------- ### Create and Emit XML Comment Node Source: https://context7.com/clojure/data.xml/llms.txt Creates an XML comment node. Comments are emitted as ''. By default, comments are dropped when the document is parsed back. ```clojure (require '[clojure.data.xml :as xml]) (xml/emit-str (xml/element :config {} (xml/xml-comment " Database settings ") (xml/element :host {} "localhost") (xml/xml-comment " Port defaults to 5432 ") (xml/element :port {} "5432"))) ;; => "localhost5432" ;; Comments are dropped on re-parse (default behavior) (xml/parse-str "") ;; => #xml/element{:tag :root, :content [#xml/element{:tag :child}]} ``` -------------------------------- ### Parse XML string with CDATA and coalescing option Source: https://github.com/clojure/data.xml/blob/master/README.md Parses an XML string, demonstrating the handling of CDATA sections. Set :coalescing to false to preserve CDATA as separate content. ```clojure (xml/parse-str "" :coalescing false) ``` -------------------------------- ### emit-str Source: https://context7.com/clojure/data.xml/llms.txt Returns the XML representation of an element tree as a `String`. Accepts the same `:encoding` and `:doctype` options as `emit`. Useful for testing and debugging. ```APIDOC ## `emit-str` — Serialize an element tree to a String Returns the XML representation of an element tree as a `String`. Accepts the same `:encoding` and `:doctype` options as `emit`. Useful for testing and debugging. ```clojure (require '[clojure.data.xml :as xml]) (xml/emit-str (xml/element :foo {:foo-attr "foo value"} (xml/element :bar {:bar-attr "bar value"} (xml/element :baz {} "The baz value")))) ;; => "The baz value" ;; Verify round-trip fidelity (let [tree (xml/element :root {:version "1"} (xml/element :child {} "data"))] (= tree (xml/parse-str (xml/emit-str tree)))) ;; => true ;; Various Clojure types are auto-serialized to XML strings (xml/emit-str (xml/element :data {} true ;; "true" 42 ;; "42" 3/4 ;; "0.75" (java.util.Date. 0))) ;; "1970-01-01T00:00:00.000-00:00" ``` ``` -------------------------------- ### indent / indent-str Source: https://context7.com/clojure/data.xml/llms.txt Re-emits XML with indentation for human readability. Internally emits to a string and re-parses via `javax.xml.transform`, making it slow. Intended for debugging and development only. ```APIDOC ## `indent` / `indent-str` — Pretty-print XML with indentation Re-emits XML with indentation for human readability. Internally emits to a string and re-parses via `javax.xml.transform`, making it slow. Intended for debugging and development only. ```clojure (require '[clojure.data.xml :as xml]) (print (xml/indent-str (xml/element :catalog {} (xml/element :book {:id "bk101"} (xml/element :title {} "XML Developer's Guide") (xml/element :price {} "44.95"))))) ;; => ;; ;; ;; ;; XML Developer's Guide ;; 44.95 ;; ;; ;; Write indented output directly to a Writer (with-open [out (clojure.java.io/writer "pretty.xml")] (xml/indent (xml/element :root {} (xml/element :child {} "value")) out)) ``` ``` -------------------------------- ### Parse XML from a StringReader Source: https://github.com/clojure/data.xml/blob/master/README.md Parses XML content from a java.io.StringReader. The parsed data is returned as defrecords. ```clojure (let [input-xml (java.io.StringReader. " The baz value")] (xml/parse input-xml)) ``` -------------------------------- ### Emit XML with a comment Source: https://github.com/clojure/data.xml/blob/master/README.md Emits an XML element that includes an XML comment. The comment is inserted as a processing instruction. ```clojure (xml/emit-str (xml/element :foo {} (xml/xml-comment "Just a goes here") (xml/element :bar {} "and another element"))) ;; newlines added for readability, not in actual output " and another element" ``` -------------------------------- ### parse-str Source: https://context7.com/clojure/data.xml/llms.txt Parses an XML string into an element tree. It accepts the same options as the `parse` function. ```APIDOC ## `parse-str` — Parse XML from a String Convenience wrapper around `parse` that accepts an XML string directly. Accepts the same options as `parse`. ```clojure (require '[clojure.data.xml :as xml]) (xml/parse-str " Everyday Italian 30.00 ") ;; => #xml/element{:tag :bookstore, :attrs {}, ;; :content [#xml/element{:tag :book, ;; :attrs {:category "cooking"}, ;; :content [#xml/element{:tag :title ...} ;; #xml/element{:tag :price ...}]}]} ;; Round-trip: parse → manipulate → re-emit (let [doc (xml/parse-str "apple") item (first (:content doc))] (println (:tag item)) ;; :item (println (:attrs item)) ;; {:id "1"} (println (first (:content item)))) ;; "apple" ;; Parsing with namespace awareness disabled (xml/parse-str "100" :namespace-aware false) ;; => #xml/element{:tag :limit, :attrs {:xmlns.http%3A...%2F/D "DAV:"}, ...} ``` ``` -------------------------------- ### Convert Hiccup-style Vectors to XML Elements Source: https://context7.com/clojure/data.xml/llms.txt Converts Hiccup-style vectors to XML Elements. Special tags ':-cdata' and ':-comment' create CDATA and Comment nodes respectively. Use 'sexps-as-fragment' for multiple sibling elements. ```clojure (require '[clojure.data.xml :as xml]) ;; Basic Hiccup-style conversion (xml/sexp-as-element [:person {:id "1"} [:name {} "Alice"] [:age {} "30"]]) ;; => #xml/element{:tag :person, :attrs {:id "1"}, ;; :content [#xml/element{:tag :name ...} ;; #xml/element{:tag :age ...}]} ;; Equivalence with element constructor (= (xml/element :foo {:a "1"} (xml/element :bar {} "baz")) (xml/sexp-as-element [:foo {:a "1"} [:bar {} "baz"]])) ;; => true ;; Using special :-cdata and :-comment tags (xml/emit-str (xml/sexp-as-element [:root {} [:-comment "generated file"] [:data {} [:-cdata "content"]]])) ;; => " ;; content]]>" ;; sexps-as-fragment returns a seq of elements (no single root required) (xml/sexps-as-fragment [:li {} "Item 1"] [:li {} "Item 2"] [:li {} "Item 3"]) ;; => (#xml/element{:tag :li ...} #xml/element{:tag :li ...} #xml/element{:tag :li ...}) ``` -------------------------------- ### Auto-Generated Namespace Prefixes Source: https://github.com/clojure/data.xml/blob/master/README.md When a namespace prefix is not specified, data.xml auto-assigns prefixes during emission. Nested tags in the same namespace reuse the same prefix. ```clojure (xml/emit-str (xml/element ::xh/title {} "Example title")) ``` ```xml " Example title" ``` ```clojure (xml/emit-str (xml/element ::xh/html {} (xml/element ::xh/head {} (xml/element ::xh/title {} "Example title")))) ``` ```xml " Example title" ``` -------------------------------- ### emit Source: https://context7.com/clojure/data.xml/llms.txt Serializes an `Element` tree to a `java.io.Writer` or `java.io.OutputStream`. Writes a standard XML declaration header. Options allow specifying character encoding and a DOCTYPE declaration. ```APIDOC ## `emit` — Write an element tree to a Writer as XML text Serializes an `Element` tree to a `java.io.Writer` or `java.io.OutputStream`. Writes a standard XML declaration header. Options allow specifying character encoding and a DOCTYPE declaration. ```clojure (require '[clojure.data.xml :as xml] '[clojure.java.io :as io]) ;; Write to a file (let [doc (xml/element :catalog {} (xml/element :book {:id "1"} "Clojure Programming"))] (with-open [out (io/writer "output.xml")] (xml/emit doc out))) ;; Writes: Clojure Programming ;; Specify encoding (let [doc (xml/element :greeting {} "Übercool")] (with-open [out (io/output-stream "output.xml")] (xml/emit doc (java.io.OutputStreamWriter. out "ISO-8859-1") :encoding "ISO-8859-1"))) ;; Emit with a DOCTYPE declaration (let [doc (xml/element :html {} (xml/element :body {} "Hello"))] (with-open [out (io/writer "page.html")] (xml/emit doc out :doctype ""))) ``` ``` -------------------------------- ### Parse XML with Location Metadata in Clojure Source: https://github.com/clojure/data.xml/blob/master/README.md Parses an XML string and includes location information (character offset, column, and line number) as metadata under the :clojure.data.xml/location-info key. This is the default behavior. ```clojure (deftest test-location-meta (let [input "\n" location-meta (comp :clojure.data.xml/location-info meta)] (is (= 1 (-> input xml/parse-str location-meta :line-number))))) ``` -------------------------------- ### event-seq Source: https://context7.com/clojure/data.xml/llms.txt Lazy pull-parsing event sequence. Returns a lazy sequence of pull-parse events from an `InputStream` or `Reader`. Provides the lowest-level streaming access, enabling memory-efficient processing of huge XML files. An `event-seq` can also be passed directly to `emit`/`emit-str` for stream-to-stream transformation. ```APIDOC ## `event-seq` — Lazy pull-parsing event sequence ### Description Returns a lazy sequence of pull-parse events (`StartElementEvent`, `EndElementEvent`, `CharsEvent`, `CDataEvent`, `CommentEvent`) from an `InputStream` or `Reader`. Provides the lowest-level streaming access, enabling memory-efficient processing of huge XML files. An `event-seq` can also be passed directly to `emit`/`emit-str` for stream-to-stream transformation. ### Usage ```clojure (require '[clojure.data.xml :as xml]) ;; Inspect raw events (xml/event-seq (java.io.StringReader. "12") {}) ;; => (#StartElementEvent{:tag :root ...} ;; #StartElementEvent{:tag :item ...} ;; #CharsEvent{:str "1"} ;; #EndElementEvent{:tag :item ...} ;; #StartElementEvent{:tag :item ...} ;; #CharsEvent{:str "2"} ;; #EndElementEvent{:tag :item ...} ;; #EndElementEvent{:tag :root ...}) ;; Stream transformation: parse → filter → re-emit (no full tree in memory) (let [events (xml/event-seq (java.io.FileInputStream. "large.xml") {})] (xml/emit-str events)) ;; Include comment events (xml/event-seq (java.io.StringReader. "") {:include-node? #{:element :characters :comment}}) ``` ``` -------------------------------- ### Parse XML String with clojure.data.xml Source: https://context7.com/clojure/data.xml/llms.txt Use `parse-str` to parse an XML string into an element tree. It accepts the same options as `parse`. Namespace awareness can be disabled. ```clojure (require '[clojure.data.xml :as xml]) (xml/parse-str " Everyday Italian 30.00 ") ``` ```clojure ;; Round-trip: parse → manipulate → re-emit (let [doc (xml/parse-str "apple") item (first (:content doc))] (println (:tag item)) ;; :item (println (:attrs item)) ;; {:id "1"} (println (first (:content item)))) ;; "apple" ``` ```clojure ;; Parsing with namespace awareness disabled (xml/parse-str "100" :namespace-aware false) ```