source: trunk/src/xml2struct.m @ 518

Last change on this file since 518 was 477, checked in by sommeria, 13 years ago

various bugs repaired.

File size: 2.2 KB
Line 
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
11function [s,Heading]=xml2struct(filename)
12t=xmltree(filename);
13Heading=get(t,1,'name');
14ss=convert(t);
15s=convert_string(ss);
16
17
18function out=convert_string(ss)
19info=whos('ss');
20switch 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        check_numeric=zeros(size(ss));
44        for ilist=1:numel(ss)
45            if ~isempty(str2num(ss{ilist}))
46                out{ilist,1}=str2num(ss{ilist});
47                check_numeric(ilist)=1;
48            else
49                sep_ind=regexp(ss{ilist},'\s&\s');% check for separator ' & ' which indicates column separation in tables
50                if ~isempty(sep_ind)
51                    sep_ind=[-2 sep_ind length(ss{ilist})+1];
52                    for icolumn=1:length(sep_ind)-1
53                        out{ilist,icolumn}=ss{ilist}(sep_ind(icolumn)+3:sep_ind(icolumn+1)-1);
54                    end
55                else
56                    out{ilist,1}=ss{ilist}; %reproduce the input string
57                end
58            end
59        end
60        if isequal(check_numeric,ones(size(ss)))
61            out=cell2mat(out);
62        end
63    otherwise
64        out=ss;
65end
66
67   
Note: See TracBrowser for help on using the repository browser.