MATLAB Tips and Tricks

Wednesday, December 22, 2004

Creating XML outputs with MATLAB

If you want to format your data output as an XML file, here's how to do it without doing any complicated string handling. MATLAB can use the XML handling capabilities of Java very easily. Here's how:

Assume that your data is available in arrays arrData1 and arrData2. Create an XML document node, say Node1 as follows:

docNode = com.mathworks.xml.XMLUtils.createDocument('Node1');
docRootNode = docNode.getDocumentElement;


Now put the data in the data nodes..

for i=1:length(arrData1),
% create nodes..
    elPar = docNode.createElement('DataParent');
    elData1 = docNode.createElement('Data1');
    elData2 = docNode.createElement('Data2');

% put data in nodes..
    elData1.appendChild(...
docNode.createTextNode(sprintf('%f', arrData1(i))));
    elData2.appendChild(...
docNode.createTextNode(sprintf('%f', arrData2(i))));

% put nodes in the correct positions..
    elParent.appendChild(elData1);
    elParent.appendChild(elData2);
    docRootNode.appendChild(elParent);
end

Now save the XML document. You can save it directly, or use uiputfile to get the standard save dialog of the OS.

[filename, pathname] = uiputfile(...
sprintf('%s.xml', datFile), 'Save XML file as');

% Save the XML document.
% xmlFileName = [dataOutFile,'.xml'];
    xmlFileName = fullfile(pathname, filename);
    xmlwrite(xmlFileName,docNode);
% open xml file to see your output
    edit(xmlFileName);

To see more ways of using XML with MATLAB, refer to Java's documentation and play around to see what works.

5 Comments:

  • At 3:56 AM, Blogger Consul said…

    You could answer us what version could be used to save XML with matlab using java...

    Luis - Brazil

     
  • At 8:45 PM, Anonymous Anonymous said…

    where from "elParent" will come?

     
  • At 5:34 PM, Anonymous Anonymous said…

    is the DOM functionallity level exposed by MATLAB dependant on the version of JAXP being used by MATLAB?

     
  • At 11:18 AM, Anonymous Anonymous said…

    how to add attributes in headers like
    marketRequest marketDataRef="md1" marketDataXpathRef="/Rosetta/market/marketData" /

    &

    - Rosetta version="3.3"

     
  • At 4:58 AM, Anonymous Aldor said…

    Nice, thanks.

    Only instead:
    % create nodes..
    elPar = docNode.createElement('DataParent');

    should be
    % create nodes..
    elParent = docNode.createElement('DataParent');


    and instead:

    [filename, pathname] = uiputfile(...
    sprintf('%s.xml', datFile), 'Save XML file as');

    should be

    [filename, pathname] = uiputfile(...
    sprintf('%s.xml', 'datFile'), 'Save XML file as');

     

Post a Comment

<< Home