from
STRUCT2XML4EXCEL
by Scott Frasso
Write a large struct to xml for edting in Excel, and load it back into a struct.
|
| xml2struct(xmlFileName)
|
function structure= xml2struct(xmlFileName)
%XML2STRUCT takes an properly formatted XML file and returns a struct
%
% struct = XML2STRUCT('myXMLFile.xml') will take the properly formatted
% xml file and return a structure containing the information from the XML
% file. This method is meant to be used in conjunction with STRUCT2XML.
%
% The purpose of this file was to save large structs to XML files so they
% could be loaded into Excel and edited using Excel's XML editing
% capabilities.
%
% Example, using a PROPERLY formatted xml file to make a struct
%
% myXMLFile.xml looks like this:
% <?xml version="1.0" encoding="utf-8"?>
% <root_element>
% <Tree>
% <StructEntry>
% <Name>MyName</Name>
% <FooArray1>a</FooArray1>
% <FooArray2>b</FooArray2>
% <FooArray3>c</FooArray3>
% </StructEntry>
% <StructEntry>
% <Name>MyOtherName</Name>
% <FooArray1>d</FooArray1>
% <FooArray2>e</FooArray2>
% <FooArray3>f</FooArray3>
% </StructEntry>
% </Tree>
% </root_element>
%
% struct = xml2struct('myXMLFile.xml');
% The resulting struct will look like this
% testStruct(1).Name = 'MyName';
% testStruct(1).FooArray = {'a' 'b' 'c'};
% testStruct(2).Name = 'MyOtherName';
% testStruct(2).FooArray = {'d' 'e' 'f'};
%
% see also struct2xml
%
xmlDocument = xmlread(xmlFileName);
xmlDocumentElement = xmlDocument.getDocumentElement();
structEntryList = xmlDocumentElement.getElementsByTagName('StructEntry');
structure = struct();
for idx = 1:structEntryList.getLength()
structEntry = structEntryList.item(idx-1);
structEntryChildNodes = structEntry.getChildNodes();
for fieldsIdx = 1:structEntryChildNodes.getLength()
childNode = structEntryChildNodes.item(fieldsIdx-1);
if ~strcmp('#text',childNode.getNodeName)
% This is a valid node
if any(regexp(char(childNode.getNodeName),'\w+\d+'))
% This is part of a cell
indexNumber = regexp(char(childNode.getNodeName()),'\d+','match');
indexNumber = str2num(indexNumber{1});
fieldName = regexp(char(childNode.getNodeName()),'[A-z]+','match');
fieldName = fieldName{1};
if ~isfield(structure,fieldName)
structure.(fieldName) = {};
end
structure(idx).(fieldName){indexNumber} = char(childNode.getTextContent());
else
% This is just a regular field
fieldName = char(childNode.getNodeName());
if ~isfield(structure,fieldName)
structure.(fieldName) = '';
end
structure(idx).(fieldName) = char(childNode.getTextContent());
end
end
end
end
|
|
Contact us at files@mathworks.com