Matlab读取.xml文件并写入struct

1.官方函数

xmlread读取 XML 文档并返回文档对象模型节点

但是这个函数得到的文档对象模型节点中的内容无法查看

于是官方给出了一个将XML文件读入结构体数组中的函数 parseXML.m

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.',filename);
end


% ----- Local function PARSECHILDNODES -----
function children = parseChildNodes(theNode)
% Recurse over node children.
children = [];
if theNode.hasChildNodes
   childNodes = theNode.getChildNodes;
   numChildNodes = childNodes.getLength;
   allocCell = cell(1, numChildNodes);

   children = struct(             ...
      'Name', allocCell, 'Attributes', allocCell,    ...
      'Data', allocCell, 'Children', allocCell);

    for count = 1:numChildNodes
        theChild = childNodes.item(count-1);
        children(count) = makeStructFromNode(theChild);
    end
end

% ----- Local function 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

% ----- Local function 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

2.使用示例

用记事本创建一个XML格式的文件demo.xml

<?xml version="1.0" encoding="UTF-8"?>
<file>
    <student-1>
        <id>171402</id>
        <name>Amy</name>
        <age>14</age>
    </student-1>
    <student-2>
        <id>171403</id>
        <name>Mike</name>
        <age>15</age>
    </student-2>
    <student-3>
        <id>171405</id>
        <name>John</name>
        <age>13</age>
    </student-3>    
</file>

调用函数

theStruct = parseXML('demo.xml');

得到结构体theStruct

第一层主节点file

第二层3个子节点student-i(i=1,2,3)

第三层子节点的子节点

扫描二维码关注公众号,回复: 13328298 查看本文章

第四层

theStruct.Children(2)是student-1

theStruct.Children(2).Children(4)是student-1的name

theStruct.Children(2).Children(4).Children.Data是'Amy'

猜你喜欢

转载自blog.csdn.net/qq_42276781/article/details/116456657
今日推荐