1 | % 'xml2struct': read an xml file as a Matlab structure, converts numeric character strings into numbers |
---|
2 | %----------------------------------------------------------------------- |
---|
3 | % function s=xml2struct(filename) |
---|
4 | % |
---|
5 | % OUTPUT: |
---|
6 | % s= Matlab structure corresponding to the input xml file |
---|
7 | % |
---|
8 | % INPUT: |
---|
9 | % filename: name of the xml file |
---|
10 | |
---|
11 | function [s,Heading]=xml2struct(filename) |
---|
12 | t=xmltree(filename); |
---|
13 | Heading=get(t,1,'name'); |
---|
14 | ss=convert(t); |
---|
15 | s=convert_string(ss); |
---|
16 | |
---|
17 | |
---|
18 | function out=convert_string(ss) |
---|
19 | info=whos('ss'); |
---|
20 | switch info.class |
---|
21 | case 'struct' |
---|
22 | out=[];%default |
---|
23 | names = fieldnames(ss); |
---|
24 | for k=1:length(names) |
---|
25 | out.(names{k})=convert_string(ss.(names{k})); |
---|
26 | end |
---|
27 | case 'char' |
---|
28 | if isempty(regexp(ss,'^(-*\d+\.*\d*\ *)+$'))% if the string does not contains a set of numbers (with possible sign and decimal) separated by blanks |
---|
29 | sep_ind=regexp(ss,'\s&\s');% check for separator ' & ' which indicates column separation in tables |
---|
30 | if ~isempty(sep_ind) |
---|
31 | sep_ind=[-2 sep_ind length(ss)+1]; |
---|
32 | for icolumn=1:length(sep_ind)-1 |
---|
33 | out{1,icolumn}=ss(sep_ind(icolumn)+3:sep_ind(icolumn+1)-1); |
---|
34 | end |
---|
35 | else |
---|
36 | out=ss; %reproduce the input string |
---|
37 | end |
---|
38 | else |
---|
39 | out=str2num(ss); |
---|
40 | end |
---|
41 | case 'cell' |
---|
42 | out=[];%default |
---|
43 | if isequal(cellfun(@isnumeric,ss),ones(size(ss)))% if the all the cell content is numeric |
---|
44 | out=cell2mat(ss); |
---|
45 | else |
---|
46 | for ilist=1:numel(ss) |
---|
47 | sep_ind=regexp(ss{ilist},'\s&\s');% check for separator ' & ' which indicates column separation in tables |
---|
48 | if ~isempty(sep_ind) |
---|
49 | sep_ind=[-2 sep_ind length(ss{ilist})+1]; |
---|
50 | for icolumn=1:length(sep_ind)-1 |
---|
51 | out{ilist,icolumn}=ss{ilist}(sep_ind(icolumn)+3:sep_ind(icolumn+1)-1); |
---|
52 | end |
---|
53 | else |
---|
54 | out{ilist,1}=ss{ilist}; %reproduce the input string |
---|
55 | end |
---|
56 | end |
---|
57 | end |
---|
58 | % for ilist=1:numel(ss) |
---|
59 | % if ~isempty(str2num(ss{ilist})) |
---|
60 | % out(ilist,:)=str2num(ss{ilist});% convert to numeric |
---|
61 | % end |
---|
62 | % end |
---|
63 | otherwise |
---|
64 | out=ss; |
---|
65 | end |
---|
66 | |
---|
67 | |
---|