xmlread

Считайте XML-документ и возвратите узел Объектной модели документа

Описание

пример

DOMnode = xmlread(filename) читает заданный XML-файл и возвращает DOMnode узел Объектной модели документа, представляющий документ.

Работа с xmlread требует, чтобы вы использовали Java® API для обработки XML (JAXP). Для получения дополнительной информации см. https://docs.oracle.com/javase/7/docs/api.

пример

DOMnode = xmlread(filename,'AllowDoctype',tf) также задает, разрешены ли объявления DOCTYPE. Если tf false, чтение входного XML-файла, содержащего объявления DOCTYPE, приводит к ошибке. В противном случае, xmlread возвращает выход DOMnode для XML-файла. Значение по умолчанию tf true.

Примеры

свернуть все

Исследуйте содержимое демонстрационного XML-файла и затем считайте XML-файл в узел Объектной модели документа (DOM).

Отобразите содержимое файла sample.xml.

sampleXMLfile = 'sample.xml';
type(sampleXMLfile)
<productinfo> 

<matlabrelease>R2012a</matlabrelease>
<name>Example Manager</name>
<type>internal</type>
<icon>ApplicationIcon.DEMOS</icon>

<list>
<listitem>
<label>Example Manager</label>
<callback>com.mathworks.xwidgets.ExampleManager.showViewer
</callback>
<icon>ApplicationIcon.DEMOS</icon>
</listitem>
</list>

</productinfo>

Считайте XML-файл в узел DOM.

DOMnode = xmlread(sampleXMLfile);

Создайте функцию парсинга, чтобы считать XML-файл в структуру MATLAB®, и затем считать демонстрационный XML-файл в рабочее пространство MATLAB.

Создать функциональный parseXML, скопируйте и вставьте этот код в m-файл parseXML.m, или используйте parseXML.m включенный в этот пример. parseXML функционируйте данные о синтаксических анализах из XML-файла в массив структур MATLAB с полями NameАтрибутыданные, и Children.

type('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

Используйте parseXML функционируйте, чтобы проанализировать файл примера info.xml в структуру MATLAB.

sampleXMLfile = 'info.xml';
mlStruct = parseXML(sampleXMLfile)
mlStruct = struct with fields:
          Name: 'productinfo'
    Attributes: [1x2 struct]
          Data: ''
      Children: [1x13 struct]

Входные параметры

свернуть все

Имя файла в виде вектора символов или строкового скаляра, содержащего имя локального файла или URL.

Типы данных: char | string

Представлено до R2006a
Для просмотра документации необходимо авторизоваться на сайте