1 | % PARSEXML Convert XML file to a MATLAB structure. (from matlab help) |
---|
2 | function theStruct = parseXML(filename) |
---|
3 | |
---|
4 | try |
---|
5 | tree = xmlread(filename); |
---|
6 | catch |
---|
7 | error('Failed to read XML file %s.',filename); |
---|
8 | end |
---|
9 | |
---|
10 | % Recurse over child nodes. This could run into problems |
---|
11 | % with very deeply nested trees. |
---|
12 | try |
---|
13 | theStruct = parseChildNodes(tree); |
---|
14 | catch |
---|
15 | error('Unable to parse XML file %s.'); |
---|
16 | end |
---|
17 | |
---|
18 | |
---|
19 | % ----- Subfunction PARSECHILDNODES ----- |
---|
20 | function children = parseChildNodes(theNode) |
---|
21 | % Recurse over node children. |
---|
22 | children = []; |
---|
23 | if theNode.hasChildNodes |
---|
24 | childNodes = theNode.getChildNodes; |
---|
25 | numChildNodes = childNodes.getLength; |
---|
26 | allocCell = cell(1, numChildNodes); |
---|
27 | |
---|
28 | children = struct( ... |
---|
29 | 'Name', allocCell, 'Attributes', allocCell, ... |
---|
30 | 'Data', allocCell, 'Children', allocCell); |
---|
31 | |
---|
32 | for count = 1:numChildNodes |
---|
33 | theChild = childNodes.item(count-1); |
---|
34 | children(count) = makeStructFromNode(theChild); |
---|
35 | end |
---|
36 | end |
---|
37 | |
---|
38 | % ----- Subfunction MAKESTRUCTFROMNODE ----- |
---|
39 | function nodeStruct = makeStructFromNode(theNode) |
---|
40 | % Create structure of node info. |
---|
41 | |
---|
42 | nodeStruct = struct( ... |
---|
43 | 'Name', char(theNode.getNodeName), ... |
---|
44 | 'Attributes', parseAttributes(theNode), ... |
---|
45 | 'Data', '', ... |
---|
46 | 'Children', parseChildNodes(theNode)); |
---|
47 | |
---|
48 | if any(strcmp(methods(theNode), 'getData')) |
---|
49 | nodeStruct.Data = char(theNode.getData); |
---|
50 | else |
---|
51 | nodeStruct.Data = ''; |
---|
52 | end |
---|
53 | |
---|
54 | % ----- Subfunction PARSEATTRIBUTES ----- |
---|
55 | function attributes = parseAttributes(theNode) |
---|
56 | % Create attributes structure. |
---|
57 | |
---|
58 | attributes = []; |
---|
59 | if theNode.hasAttributes |
---|
60 | theAttributes = theNode.getAttributes; |
---|
61 | numAttributes = theAttributes.getLength; |
---|
62 | allocCell = cell(1, numAttributes); |
---|
63 | attributes = struct('Name', allocCell, 'Value', allocCell); |
---|
64 | |
---|
65 | for count = 1:numAttributes |
---|
66 | attrib = theAttributes.item(count-1); |
---|
67 | attributes(count).Name = char(attrib.getName); |
---|
68 | attributes(count).Value = char(attrib.getValue); |
---|
69 | end |
---|
70 | end |
---|