XPath and IMT: Namespace Prefixes

With complex XML schemas, it is at times necessary to use the XPath features in IMT to map attributes or elements to column definitions. The basic idea of how this works is pretty simple, but there are a few “gotchas”. Elements with namespace prefixes are one of those scenarios.

Suppose you have an XML document structured like so:

<root>
    <parent1>
        <child1>value</child1>
    </parent1>
</root>

If you wanted to create an XPath to “select” the child1 element, you might write something like this:

/root/parent1/child1

This will work, but suppose the XML use namespaces like this:

<ns1:root xmlns:ns1="https://myns.mydomain.com">
    <ns1:parent1>
        <ns1:child1>value</ns1:child1>
    </ns1:parent1>
</ns1:root>

Transaction Manager doesn’t allow us to define namespaces and ignores namespace declarations in the XML itself. This means we can’t use the XPath above or even simply add the namespace prefix to our XPath. But there is a way around this limitation and it involves the use of the local-name() XPath function. By using a wildcard (*) to select “any” element, then adding a predicate that checks the local name of the element, we can effectively “ignore” the namespace entirely. Here is what the same XPath would look like using this workaround:

/*[local-name()='root']/*[local-name()='parent1']/*[local-name()='child1']

As the product continues to evolve, we may see official namespace support at some point, but this should get you by for now and even better – it is “forward compatible”, meaning namespace support will not break your workaround. Win!

Josh Johnson

Josh Johnson

Solutions Architect at TrueCommerce
Josh has been writing software for 7 years. He currently works on the .NET stack using .NET Core and Angular to build highly-customized solutions for the Professional Services team at TrueCommerce.
Josh Johnson

Latest posts by Josh Johnson (see all)