Working with namespaces in Velocity

Consider the sample snippet below:

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

In order to access the <d:Title> element here using a Velocity Format, the following methods can be used:

Method 1:

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

This approach uses an addNamespace method available to $contentRoot which allows you to save a reference to a namespace object. From there, that namespace object is passed as a second parameter to the getChild method when accessing the corresponding elements using that namespace.

Method 2:

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

This approach uses the XPathTool to select the node and output its value.

Method 3:

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

This approach is similar to Method 2 above, but can be especially useful for XML documents or RSS Feeds that contain hidden namespaces. Using XPath's local-name() function essentially ignores any namespaces and treats elements as if they are in the default namespace.