Thursday, March 13, 2008

XMLSearch(), Namespaces, and Lack of Namespaces

I ran into a similar issue using xquery in SQL Server, but today I was back on the ColdFusion side of the world and had to fix it slightly differently.


In the application I'm working on I'm processing tons of XML files and depending on how they're generated, they may or may not have a namespace declared. Luckily other than that the XML structure is consistent, but XmlSearch() in CF behaves differently depending on whether or not a namespace is present.


Luckily I came across this post by Jeremy at his aftergeek blog that solved the issue for me (and to reiterate what I said in another post, I'm a bit of an xpath n00b). Using the local-name() function gets at the XML data correctly both when a namespace is present and when it isn't. So where I was previously doing this:



<cfset foo = XmlSearch(myxml, "/*/mynode").get(0).XmlText />



I'm now doing this:



<cfset foo = XmlSearch(myxml, "//*[local-name()='mynode']").get(0).XmlText />



Blogging this mostly so I don't forget myself, but I also thought others might be interested. Time for me to get an xpath book or something and learn this stuff for real. ;-)


Comments



Very useful info Matt thanks for the post.





I thank you.


My forehead thanks you.


My wall thanks you.





I see that this thread is old - but it is clearly not dead. I just wanted to add my two cents:


If you are working with XML from an Excel 2003 Document (which is riddled with namespaces) this is the XML Search code I used to get at a worksheets rows:


subsiteXML = xmlSearch(mapXML, "//ss:Worksheet/ss:Table/ss:Row")


until CF 9 comes out anyways





Thanks Ron--handy tip!



No comments: