Home > . > parseXML.m

parseXML

PURPOSE ^

PARSEXML Convert XML file to a MATLAB structure. (from matlab help)

SYNOPSIS ^

function theStruct = parseXML(filename)

DESCRIPTION ^

 PARSEXML Convert XML file to a MATLAB structure. (from matlab help)

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SUBFUNCTIONS ^

SOURCE CODE ^

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

Generated on Fri 13-Nov-2009 11:17:03 by m2html © 2003