-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVOCxml2struct.m
97 lines (86 loc) · 2 KB
/
VOCxml2struct.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
function res = VOCxml2struct(xml)
xml(xml==9|xml==10|xml==13)=[];
[res,xml]=parse(xml,1,[]);
function [res,ind]=parse(xml,ind,parent)
res=[];
xml=strrep(xml,' ','');
xml=strrep(xml,' verified="no"','');
if ~isempty(parent)&&xml(ind)~='<'
i=findchar(xml,ind,'<');
res=trim(xml(ind:i-1));
ind=i;
[tag,ind]=gettag(xml,i);
if ~strcmp(tag,['/' parent])
tag,parent
xml
error('<%s> closed with <%s>',parent,tag);
end
else
while ind<=length(xml)
[tag,ind]=gettag(xml,ind);
if strcmp(tag,['/' parent])
return
else
[sub,ind]=parse(xml,ind,tag);
if isstruct(sub)
if isfield(res,tag)
n=length(res.(tag));
fn=fieldnames(sub);
for f=1:length(fn)
res.(tag)(n+1).(fn{f})=sub.(fn{f});
end
else
res.(tag)=sub;
end
else
if isfield(res,tag)
if ~iscell(res.(tag))
res.(tag)={res.(tag)};
end
res.(tag){end+1}=sub;
else
res.(tag)=sub;
end
end
end
end
end
function i = findchar(str,ind,chr)
i=[];
while ind<=length(str)
if str(ind)==chr
i=ind;
break
else
ind=ind+1;
end
end
function [tag,ind]=gettag(xml,ind)
if ind>length(xml)
tag=[];
elseif xml(ind)=='<'
i=findchar(xml,ind,'>');
if isempty(i)
error('incomplete tag');
end
tag=xml(ind+1:i-1);
ind=i+1;
else
xml
xml(ind)
ind
error('expected tag');
end
function s = trim(s)
for i=1:numel(s)
if ~isspace(s(i))
s=s(i:end);
break
end
end
for i=numel(s):-1:1
if ~isspace(s(i))
s=s(1:i);
break
end
end