How to Import Parameters from XML file into Matlab Workspace

I have XML file similar to follows:
I want to import parameters listed in above xml file to Matlab base workspace as follows:
How it can be achieved using Matlab Script? And above functionality can be achieved using pushbutton in GUI?

 Accepted Answer

xmldoc = xmlread( filename );
x0 = str2double( xmldoc.getElementsByTagName( 'x0' ).item( 0 ).getFirstChild.getNodeValue( ) );
x1 = str2double( xmldoc.getElementsByTagName( 'x1' ).item( 0 ).getFirstChild.getNodeValue( ) );
x2 = str2double( xmldoc.getElementsByTagName( 'x2' ).item( 0 ).getFirstChild.getNodeValue( ) );
works if that is as complicated as your file gets. If you have x0 etc in other places too then you'd need to find specifically the 'states' node first.
There may be simpler ways, but I always get lost in the functions for reading XML - they never seem at all intuitive or easy to debug. Generally I split into more lines with intermediate variables.
Also I would read those into a single vector x as x(1), x(2), x(3), but the above does what you asked.

2 Comments

Thanks for your answer! I have one query over here, can we create variable names dynamically? for e.g. x0, x1 need to have always tab names mentioned in XML file not the predefined variable names.
Variable names are just something you use in code - they shouldn't need to be locked to anything external. As I mentioned, you should be reading that data into a vector ideally.
Since Matlab vectors index from 1 rather than 0 it does at a little confusion that the indexing is off by one, but it is far neater.
If you really need to replicate the structure of the XML file though then read into fields of a struct which can be dynamically named.
e.g.
fieldName = 'x0';
myStruct.( fieldname ) = ...

Sign in to comment.

More Answers (0)

Tags

Asked:

on 1 Feb 2017

Commented:

on 1 Feb 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!