Simplest way to convert XML to a map?

Simplest way to convert XML to a map?

I've reviewed the help info and some great posts on the forum here by Stephen Rhyne ( srhyne).

At the moment I'm using XPath to generate a list of xml nodes, iterating through that to fetch the field name/value pairs and adding them to a map (one map for each record in the data). I then convert the row map to a string and add it to a list.

Here's the function:
  1. list xml.getRecordListFromXML(string xml_data, string ele_name)
  2. {
  3.     result = List();
  4.     // get list of record nodes
  5.     rec_list = input.xml_data.toXML().executeXPath("//" + input.ele_name).toXmlList();
  6.     // get a map ready
  7.     rec_map = map();
  8.     // iterate through records
  9.     for each rec in rec_list
  10.     {
  11.         // get list of field nodes
  12.         field_list = rec.executeXPath("/" + input.ele_name + "/*").toXmlList();
  13.         // iterate through fields
  14.         for each field in field_list
  15.         {
  16.             str_field = field.toString();
  17.             // get field name
  18.             s_index = ((str_field).indexOf("<")  +  1);
  19.             e_index = (str_field).indexOf(">");
  20.             name = (str_field).subString(s_index,e_index);
  21.             name = (name).replaceFirst(("\s+.*"),"");
  22.             // get field value
  23.             value = field.executeXPath("/" + name + "/text()");
  24.             // add to row map
  25.             rec_map.put(name, value);
  26.         }
  27.         // add record to list as string
  28.         result.add(rec_map.toString());
  29.     }
  30.     return result;
  31. }

This returns a list of map strings which can easily be looped and converted back into maps to grab the field values for each row/record.

Another benefit of the above approach is that the field names do not need to be known in advance.

Does anyone know of an easier way? I am assuming there is no built-in Deluge function for converting an XML string to a map (or to a JSON string, which can then be converted to a map)?

Since we already have map_var.toXML() I was thinking i t would be great to have something like this:

xml_string.toMap()
...and/or:
xml_string.toJSON()


Anton