Code covered by the BSD License  

Highlights from
Supply Chain Risk Simulator (SCRS)

from Supply Chain Risk Simulator (SCRS) by Marco Anisetti
Supply Chain simulator for risk assessment and incentive schemes.

parseXML(filename)
function theStruct = parseXML(filename)
% PARSEXML Convert XML file to a MATLAB structure.
try
   tree = xmlread(filename);
catch
   error('Failed to read XML file %s.',filename);
end

% Recurse over child nodes. This could run into problems 
% with very deeply nested trees.
try
   theStruct = parseChildNodes(tree);
catch
   error('Unable to parse XML file %s.');
end


% ----- Subfunction PARSECHILDNODES -----
function children = parseChildNodes(theNode)
% Recurse over node children.
% TheDOM includes some #text where between children
% so the dimension is dim-1/2
children = [];
if theNode.hasChildNodes
   % la prima volta devo stare attento
   childNodes = theNode.getChildNodes;
   numChildNodes = (childNodes.getLength-1)/2;
   allocCell = cell(1, numChildNodes);

   children = struct(             ...
      'Name', allocCell, 'Attributes', allocCell,    ...
      'Data', allocCell, 'Children', allocCell);
    contatore=1; % contatore vero della struttura allocata
    
    for count = 1:childNodes.getLength
        theChild = childNodes.item(count-1);
        if not(strcmp(theChild.getNodeName,'#text'))
           children(contatore) = makeStructFromNode(theChild);   
           contatore=contatore+1;
        end    
    end
end

% ----- Subfunction MAKESTRUCTFROMNODE -----
function nodeStruct = makeStructFromNode(theNode)
% Create structure of node info.

nodeStruct = struct(                        ...
   'Name', char(theNode.getNodeName),       ...
   'Attributes', parseAttributes(theNode),  ...
   'Data', '',                              ...
   'Children', parseChildNodes(theNode));

if any(strcmp(methods(theNode), 'getData'))
   nodeStruct.Data = char(theNode.getData); 
else
   nodeStruct.Data = '';
end

% ----- Subfunction PARSEATTRIBUTES -----
function attributes = parseAttributes(theNode)
% Create attributes structure.

attributes = [];
if theNode.hasAttributes
   theAttributes = theNode.getAttributes;
   numAttributes = theAttributes.getLength;
   allocCell = cell(1, numAttributes);
   attributes = struct('Name', allocCell, 'Value', allocCell);

   for count = 1:numAttributes
      attrib = theAttributes.item(count-1);
      attributes(count).Name = char(attrib.getName);
      attributes(count).Value = char(attrib.getValue);
   end
end

Contact us at files@mathworks.com