Считайте XML-документ и возвратите узел Объектной модели документа
DOMnode = xmlread (имя файла)
читает заданный XML-файл и возвращает узел Объектной модели документа, представляющий документ.DOMnode = xmlread(filename)
|
Имя файла, заданное как вектор символа или скаляр строки, содержащий имя локального файла или URL. |
|
Узел Объектной модели документа, как задано консорциумом Всемирной паутины. Для получения дополнительной информации смотрите то, Что Объектная модель XML-документов (DOM)?. |
Корневой элемент в XML-файле иногда включает атрибут xsi:noNamespaceSchemaLocation. Значение этого атрибута является именем предпочтительного файла схемы. Вызовите метод getAttribute, чтобы получить это значение:
xDoc = xmlread(fullfile(matlabroot,'toolbox',...
'matlab','general','info.xml'));
xRoot = xDoc.getDocumentElement;
schema = char(xRoot.getAttribute('xsi:noNamespaceSchemaLocation'))Этот код возвращается:
schema = https://www.mathworks.com/namespace/info/v1/info.xsd
Создайте функции, которые анализируют данные от XML-файла в массив структур MATLAB® с полями Name, Attributes, Data и Children:
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Отображением для правильно проанализированного документа является [#document: null] пустой указатель. Например,
xDoc = xmlread('info.xml')xDoc = [#document: null]