Home > utility > parseXML.m

parseXML

PURPOSE ^

PARSEXML Convert XML file to a MATLAB structure.

SYNOPSIS ^

function theStruct = parseXML(filename)

DESCRIPTION ^

 PARSEXML Convert XML file to a MATLAB structure.

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SUBFUNCTIONS ^

SOURCE CODE ^

0001 function theStruct = parseXML(filename)
0002 % PARSEXML Convert XML file to a MATLAB structure.
0003 try
0004    tree = xmlread(filename);
0005 catch
0006    error('Failed to read XML file %s.',filename);
0007 end
0008 
0009 % Recurse over child nodes. This could run into problems
0010 % with very deeply nested trees.
0011 try
0012    theStruct = parseChildNodes(tree);
0013 catch
0014    error('Unable to parse XML file %s.');
0015 end
0016 
0017 
0018 % ----- Subfunction PARSECHILDNODES -----
0019 function children = parseChildNodes(theNode)
0020 % Recurse over node children.
0021 children = [];
0022 if theNode.hasChildNodes
0023    childNodes = theNode.getChildNodes;
0024    numChildNodes = childNodes.getLength;
0025    allocCell = cell(1, numChildNodes);
0026 
0027    children = struct(             ...
0028       'Name', allocCell, 'Attributes', allocCell,    ...
0029       'Data', allocCell, 'Children', allocCell);
0030 
0031     for count = 1:numChildNodes
0032         theChild = childNodes.item(count-1);
0033         children(count) = makeStructFromNode(theChild);
0034     end
0035 end
0036 
0037 % ----- Subfunction MAKESTRUCTFROMNODE -----
0038 function nodeStruct = makeStructFromNode(theNode)
0039 % Create structure of node info.
0040 
0041 nodeStruct = struct(                        ...
0042    'Name', char(theNode.getNodeName),       ...
0043    'Attributes', parseAttributes(theNode),  ...
0044    'Data', '',                              ...
0045    'Children', parseChildNodes(theNode));
0046 
0047 if any(strcmp(methods(theNode), 'getData'))
0048    nodeStruct.Data = char(theNode.getData); 
0049 else
0050    nodeStruct.Data = '';
0051 end
0052 
0053 % ----- Subfunction PARSEATTRIBUTES -----
0054 function attributes = parseAttributes(theNode)
0055 % Create attributes structure.
0056 
0057 attributes = [];
0058 if theNode.hasAttributes
0059    theAttributes = theNode.getAttributes;
0060    numAttributes = theAttributes.getLength;
0061    allocCell = cell(1, numAttributes);
0062    attributes = struct('Name', allocCell, 'Value', allocCell);
0063 
0064    for count = 1:numAttributes
0065       attrib = theAttributes.item(count-1);
0066       attributes(count).Name = char(attrib.getName);
0067       attributes(count).Value = char(attrib.getValue);
0068    end
0069 end

Generated on Tue 01-Jun-2010 09:50:34 by m2html © 2003