Skip to main content

Working with namespaces in Velocity

Consider this sample XML:

XML
<info xmlns:d="https://www.hannonhill.com">
   <d:Title>Hannon Hill - Cascade CMS</d:Title>
</info>

There are three ways to access the <d:Title> element from a Velocity Format.

Using addNamespace

Velocity
#set ($dNs = $contentRoot.addNamespace("d", "https://www.hannonhill.com"))
#set ($title = $contentRoot.getChild("Title", $dNs).value)
<h2>$title</h2>

The addNamespace method on $contentRoot saves a reference to a namespace object, which you then pass as a second parameter to getChild.

Using the XPath Tool with a prefix

Velocity
#set ($title = $_XPathTool.selectSingleNode($contentRoot, "d:Title").value)
<h2>$title</h2>

This uses the XPath Tool to select the node directly.

Using local-name()

Velocity
#set ($title = $_XPathTool.selectSingleNode($contentRoot, "//node()[local-name() = 'Title']").value)
<h2>$title</h2>

Similar to the previous method, but especially useful for XML documents or RSS feeds containing hidden namespaces. XPath's local-name() function ignores namespaces entirely and treats elements as if they're in the default namespace.