source: trunk/src/private/parseXML.m @ 8

Last change on this file since 8 was 8, checked in by gostiaux, 14 years ago
File size: 1.9 KB
RevLine 
[8]1% PARSEXML Convert XML file to a MATLAB structure. (from matlab help)
2function theStruct = parseXML(filename)
3
4try
5   tree = xmlread(filename);
6catch
7   error('Failed to read XML file %s.',filename);
8end
9
10% Recurse over child nodes. This could run into problems
11% with very deeply nested trees.
12try
13   theStruct = parseChildNodes(tree);
14catch
15   error('Unable to parse XML file %s.');
16end
17
18
19% ----- Subfunction PARSECHILDNODES -----
20function children = parseChildNodes(theNode)
21% Recurse over node children.
22children = [];
23if 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
36end
37
38% ----- Subfunction MAKESTRUCTFROMNODE -----
39function nodeStruct = makeStructFromNode(theNode)
40% Create structure of node info.
41
42nodeStruct = struct(                        ...
43   'Name', char(theNode.getNodeName),       ...
44   'Attributes', parseAttributes(theNode),  ...
45   'Data', '',                              ...
46   'Children', parseChildNodes(theNode));
47
48if any(strcmp(methods(theNode), 'getData'))
49   nodeStruct.Data = char(theNode.getData);
50else
51   nodeStruct.Data = '';
52end
53
54% ----- Subfunction PARSEATTRIBUTES -----
55function attributes = parseAttributes(theNode)
56% Create attributes structure.
57
58attributes = [];
59if 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
70end
Note: See TracBrowser for help on using the repository browser.