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:
- list xml.getRecordListFromXML(string xml_data, string ele_name)
- {
- result = List();
- // get list of record nodes
- rec_list = input.xml_data.toXML().executeXPath("//" + input.ele_name).toXmlList();
- // get a map ready
- rec_map = map();
- // iterate through records
- for each rec in rec_list
- {
- // get list of field nodes
- field_list = rec.executeXPath("/" + input.ele_name + "/*").toXmlList();
- // iterate through fields
- for each field in field_list
- {
- str_field = field.toString();
- // get field name
- s_index = ((str_field).indexOf("<") + 1);
- e_index = (str_field).indexOf(">");
- name = (str_field).subString(s_index,e_index);
- name = (name).replaceFirst(("\s+.*"),"");
- // get field value
- value = field.executeXPath("/" + name + "/text()");
- // add to row map
- rec_map.put(name, value);
- }
- // add record to list as string
- result.add(rec_map.toString());
- }
- return result;
- }
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