Simplified XPath Library for Clojure
Pull request Compare This branch is 74 commits behind kyleburton:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.



clj-xpath is a library that makes it easier to with XPath from Clojure.

Note: This library has two main branches, the master branch (this branch) is for Clojure 1.3 compatability. The clj-xpath-1.2 branch is for Clojure 1.2 compatability. Both versions of the library are available on Clojars.


For Leiningen add the following dependency to your project.clj file:

    [org.clojars.kyleburton/clj-xpath "1.4.0"]

For Maven: add the following in your pom.xml file in the `dependencies` section:



Documentation is available here


Simplified XPath Library for Clojure. XML Parsers and an XPath implementation now comes with Java 6, though using the api directly can be verbose and confusing. This library provides a thin layer around basic parsing and XPath interaction for common use cases. I have personally found the ability to interactively tweak my xpath expressions to be a great productivity boost – even using this library only for that has helped me in my learning of and using xpath. I hope you find it useful and would love to hear your feedback and suggestions.


The main functions in the library are $x and those named with a prefix of $x: (eg: $x:text). The rationale for choosing $x as a name was based on the FireBug xpath function and it being a short and uncommon name. These xpath functions all take the xpath expression to be executed and an XML document. They attempt to be flexible with respect to the form of the XML document may represent. If it is a string it is treated as XML, if a byte array it is used directly, if already a Document or Node (from org.w3c.dom) they are used as-is.

There are two forms of many of the functions, with one set ending with a star ‘*’. The non-suffixed forms will perform their operation on a single result node, raising an exception if there isn’t exactly one result from applying the xpath expression to the XML document. The ‘*’ suffixed forms return all of the matched nodes for further processing.

$x function returns a map containing the XML tag (as a symbol), dom Node, the text (as a string), and a map of the attributes where the keys have been converted into symbols and the values remain Strings.

(ns example
  (use [clj-xpath.core :only [$x $x:tag $x:text $x:attrs $x:attrs* $x:node]]))

(def *some-xml*
     "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
  <book title=\"Some Guide To XML\">
      <name>P.T. Xarnum</name>
      Simply the most comprehensive XML Book on the market today.
  <book title=\"Some Guide To Functional Programming\">
      <name>S. Hawking</name>
      This book is too smart for you, try 'Head first Quantum Mechanics for Dummies' instead.

;; get the top level tag:
(prn ($x:tag "/*" *some-xml*))
;; :books

;; find all :book nodes, pull the title from the attributes:
(prn (map #(-> % :attrs :title) ($x "//book" *some-xml*)))
;; ("Some Guide To XML" "Some Guide To Functional Programming")

;; same result using the $x:attrs* function:
(prn ($x:attrs* "//book" *some-xml* :title))
;; ("Some Guide To XML" "Some Guide To Functional Programming")

;; first select the :book element who's title has 'XML' in it
;; from that node, get and print the author's name (text content):
(prn ($x:text "./author/name"
              ($x:node "//book[contains(@title,'XML')]" *some-xml*)))
;; "P.T. Xarnum"

API Reference

($x xpexpr doc) => (map [...])

This is the main xpath application function. It takes an xpath expression (as a string) and a document and returns a sequence of matched elements as maps. The map contains the node’s tag, attributes, text content and the dom Node itself.

  { :tag    :tag-name
    :attrs  { :a "map" :of "the attributes" }
    :text   "the body content of the node and it's children"
    :node   org.w3c.dom.Node }

($x:tag* xpexpr doc) => [:tag-name ...]
($x:text* xpexpr doc) => ["the content" ..]
($x:attrs* xpexpr doc) => [{:the "attrs" ...} ...]
($x:node* xpexpr doc) => [org.w3c.dom.Node ...]

These functions apply the xpath expression to the given document and return a sequence of the requested property.

($x:tag? xpexpr doc) => [:tag-name ...]
($x:text? xpexpr doc) => ["the content" ..]
($x:attrs? xpexpr doc) => [{:the "attrs" ...} ...]
($x:node? xpexpr doc) => [org.w3c.dom.Node ...]

These functions apply the xpath expression to the given document and return either nil or the single result found. Unlinke the singleton forms, these do not throw and exception (just returning nil).

($x:tag+ xpexpr doc) => [:tag-name ...]
($x:text+ xpexpr doc) => ["the content" ..]
($x:attrs+ xpexpr doc) => [{:the "attrs" ...} ...]
($x:node+ xpexpr doc) => [org.w3c.dom.Node ...]

These functions apply the xpath expression to the given document and return multiple results – throwing an exception if the xpath expression matches no elements.

($x:tag xpexpr doc) => :tag-name
($x:text xpexpr doc) => "the content"
($x:attrs xpexpr doc) => {:the "attrs" ...}
($x:node xpexpr doc) => org.w3c.dom.Node

These functions return the requested property from the single result of executing the xpath expression. If the xpath expression identifies less than 1 result or more than 1 result in the given document, an exception is raised.

(xml->doc doc) => Document

This function takes xml that is of one of the following types and returns a Document: String, byte array or org.w3c.dom.Document. In cases of repeated usage of the document (eg: executing multiple xpath expressions against the same document) this will improve performance.

($x:compile xpexpr) => javax.xml.xpath.XPathExpression

Pre-compiles the xpath expression. In cases of repeated execution of the xpath expression this will improve performance.

Parsing and XPath Compilation

The $x and related functions support Strings, and in many cases, other convenient types for these arguments. In all cases where it expects an XML Document it can be given a String, a byte array or a Document. Where an xpath expression is expected it will take either a String or a pre-compiled XPathExpression. The act of parsing an XML document or compiling an xpath expression is an expensive activity. With this flexibility, clj-xpath supports the convenience of in-line usage (with String data), as well as pre-parsed and pre-compiled instances for better performance.

  (let [expr (xp:compile "/*")
        doc  (xml->doc "<authors><author><name>P.T. Xarnum</name></author></authors>")]
    ($x:tag expr doc))


Validation now off by default. Validation is controlled by optional parameters passed to xml-bytes->dom, or by overriding the atom *validation* to false:

  (ns your.namespace
    (:use clj-xpath.core))

  (binding [*validation* false]
    ($x:text "/this" "<this>foo</this>"))

XPath and XML Namespaces

To use the xpath library with an XML document that utilizes XML namespaces, you can make use of the `with-namespace-context` macro providing a map of aliases to the xmlns URL:

  (def xml (slurp "fixtures/namespace1.xml"))
  (with-namespace-context {"atom" ""}
    ($x:text "//atom:title" xml-doc))
  ;; => BookingCollection

There is also a utility function that can pull the namespace declarations from the root node of your XML document:

  (def xml (slurp "fixtures/namespace1.xml"))
  (with-namespace-context (xmlnsmap-from-root-node xml-doc)
    ($x:text "//atom:title" xml-doc))
  ;; => BookingCollection

These two examples assume the following XML document:

<atom:feed xml:base="http://nplhost:8042/sap/opu/sdata/IWFND/RMTSAMPLEFLIGHT/"



<atom:content type="application/xml"/>



Version 1.4.0 : Tue Dec 18 15:10:19 EST 2012
  • :children lazy seq of a Node’s children added by mtnygard
  • idiomatic use of next


  • Kyle Burton <>
  • Trotter Cashion <>
  • Michael Nygard <>