XPath, xmlSearch, and Namespaces

I've been doing a bunch of XML stuff over the past few days, and ran
into an interesting issue.  If you have a default namespace
defined in a document that you're going to run xmlSearch on, you have
to respect that namespace.  What does that mean?  You need to
prefix your element names with a colon.  Take these three examples
(for searching an RSS feed):

XMLSearch(rss,"/rdf:RDF/item")
XMLSearch(rss,"/rdf:RDF/:item")
XMLSearch(rss,"//:item")

The first one doesn't work, because the 'item' element belongs to
the default namespace, not to the null namespace, so it needs to be
explicitly qualified as in the second and third lines.

Much thanks to Pete Freitag and Sean Corfield (the 3rd comment) for making this solution known.

5 responses to “XPath, xmlSearch, and Namespaces”

  1. Raymond Camden

    I ran into the same issue trying to parse RSS 1 and 2 in the same code. I ended up using this string, and it seemed to work just fine:

    //*[local-name() = 'item']

  2. Barney

    That wouldn't work in all cases. What if you have two separate namespaces that both have an 'item' element?

    Much better to explicitly specify the namespace of the particular element you want, just specifying the default namespace is not at all obvious (at least wasn't to me).

  3. Niklas Richardson

    Hi Barney,

    I also bumped into an annoying bug in CFMX 6.1 when using XMLSearch and when you have an xPathString that is very long.

    If the xPathString is too long you get an ArrayOutOfBound error thrown from ColdFusion. Beautiful!

    Here's the link and workaround:

    http://www.prismix.com/blog/archives/2005/05/bug_in_xmlsearc.cfm

  4. sher

    internet advertising internet advertising free advertising free advertising advertising specialties advertising specialties home depot home depot work at home work at home home based business home based business internet marketing internet marketing network marketing network marketing search engine marketing search engine marketing better business bureau better business bureau home based business home based business business cards business cards shopping cart shopping cart ecommerce shopping cart ecommerce shopping cart shopping cart software shopping cart software house plans house plans white house white house full house full house

  5. Clayton Davis

    One of those ridiculous caveats of XML and XPath; thanks for the tip. If Adobe cared to document or at least cross-reference a resource for XPath….