tech @ Beacon Deacon

Parse AJAX data containing XML nodes with namespaces

Jamie Johnson

November 10, 2017

Say you use AJAX to pull in data with an XML node containing a namespace prefix and you want to parse the data from within that node.

For example, what if you have the following?
<mc:EventDate>11/10/2017</mc:EventDate> and similar such nodes in your data. Once you pull the data in using AJAX, you have a string variable and you can manipulate it. The solution is rather simple. Do a replace. More specifically, do something like following in your JavaScript after you have the data from the AJAX call:

itemdate=items[i]; // This is the <item> node on which you are iterating in the AJAX script
itemdate=itemdate.toString(); // this makes sure I can do the string methods like replace()
itemdate=itemdate.replace(/mc:EventDate/g,"mcEventDate"); // globally changing the node to a parser-friendly format
itemdate=itemdate.replace(/\/mc:EventDate/g,"/mcEventDate");// escaped the closing / as I globally change the node to a parser-friendly format
itemdate=itemdate.split("<mcEventDate>");// now parse without all that grief!
itemdate=itemdate.split("</mcEventDate>");// now parse without all that grief!
itemdate=itemdate[0]; // Now I have the data originally contained in the mc:EventDate node

The bottom-line, simple solution: replace the namespace prefix node name with something parser-friendly. That's it!

Back to top