Parsing xml without elements error

I found when parsing elements in XML objects:

var varElement = XML.parse(data);
         varElement.elements.forEach(function (node) {
       var curid = node.attributes.id;
      var varname = node.attributes.name;

if there is no elements it errors out with a null and causes issues.

I tried using:
if (varElement.elements.length > 0) {
but didnt help.

I think the error happens when calling the parse. Is there a way to do this without causing and error? or Is it just as good using a TRY ERR ROUTINE:

 try {
        var varElement = XML.parse(data);
         varElement.elements.forEach(function (node) {
       var curid = node.attributes.id;
      var varname = node.attributes.name;
                var pluginDevice = new Device();
                pluginDevice.Id = "ISYState" + curid;
                //pluginDevice.Name = "ISYState_" + varname;
                pluginDevice.DisplayName = "ISYState_" + varname;
                pluginDevice.Icon = "var.png";
                pluginDevice.DeviceType = "ISYStateVariable";
                pluginDevice.TileTemplate = "ISYStateVariableTile.xaml";
                pluginDevice.DetailsTemplate = "";
                pluginDevice.Capabilities = [];
                pluginDevice.Attributes = ["ISYStateValue", "timeSet"];
                plugin.Devices[pluginDevice.Id] = pluginDevice;
               }); 
               } catch(err) {log("No State Variables");}
               }

Just want to follow best script protocol.

If that didn’t help then that means either the elements collection it self could be null or the exception is happening before during XML.parse . Find out where exactly the error is.

used try error routines on every line. The parse line was fine but just checking the length of (varElement.elements.length > 0) would error out. The next line will also error out ofcouse because there are no elements. After trying a few things the following worked:
if (varElement.elements!=null) {

Does that seem right? I tested this with several parsing routines and worked without a hitch.

Yeah, that looks correct.

Perfect this will eliminate user error when synchronizing devices if they have things enabled that they dont have. I also changed the way i handled network data to be more efficient with leftover data.(memory leak you found). I now check the data for any needed values then just delete the rest. I should be ready for new release this weekend or early next week.

2 Likes