Contenido principal

La traducción de esta página aún no se ha actualizado a la versión más reciente. Haga clic aquí para ver la última versión en inglés.

xmlread

Leer documentos XML y devolver un nodo Document Object Model

Descripción

DOMnode = xmlread(filename) lee el archivo XML especificado y devuelve un objeto de documento Xerces-J de Apache® que representa una versión analizada del archivo XML. Xerces-J de Apache implementa la API Java® para el procesamiento de XML (JAXP). Utilice funciones JAXP para manipular este objeto de documento. Para obtener más información sobre Xerces-J de Apache, consulte https://xerces.apache.org/xerces-j/apiDocs/.

ejemplo

DOMnode = xmlread(filename,'AllowDoctype',tf) también especifica si se permiten las declaraciones DOCTYPE. Si tf es false, la lectura de un archivo XML de entrada que contenga declaraciones DOCTYPE produce un error. De lo contrario, xmlread devuelve una salida DOMnode para el archivo XML. El valor predeterminado de tf es true.

ejemplo

Ejemplos

contraer todo

Examine el contenido de un archivo XML de muestra y, después, lea el archivo XML en un nodo Document Object Model (DOM).

Muestre el contenido del archivo 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>

Lea el archivo XML en un nodo DOM.

DOMnode = xmlread(sampleXMLfile);

Cree una función de análisis para leer un archivo XML en una estructura de MATLAB® y, después, lea un archivo XML de muestra en el área de trabajo de MATLAB.

Para crear la función parseXML, copie y pegue este código en un archivo m parseXML.m. La función parseXML analiza los datos de un archivo XML en un arreglo de estructuras de MATLAB con los campos Name, Attributes, Data y 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

Utilice la función parseXML para analizar el archivo de muestra info.xml en una estructura de MATLAB.

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

Argumentos de entrada

contraer todo

Nombre de archivo, especificado como vector de caracteres o escalar de cadena que contiene el nombre del archivo local o URL.

Tipos de datos: char | string

Historial de versiones

Introducido antes de R2006a