File Exchange

image thumbnail


version 1.13 (216 KB) by

Read XML files into MATLAB struct and writes MATLAB data types to XML

78 Ratings



View License

Read XML files into MATLAB struct and writes MATLAB data types to XML files, with help of simple interface to MATLAB's xmlwrite and xmlread functions.

Two function to simplify reading and writing XML files from MATLAB:

* Function xml_read first calls MATLAB's xmlread function and than converts its output ('Document Object Model' tree of Java objects) to tree of MATLAB struct's. The output is often in format of nested structs and cells. In the output data structure field names are based on XML tags.

* Function xml_write first convert input tree of MATLAB structs and cells and other types to tree of 'Document Object Model' nodes, and then writes resulting object to XML file using MATLAB's xmlwrite function.

This package can:
* Read any XML file, possibly created outside of MATLAB, and convert it to MATLAB data structures.
* Write any MATLAB's struct tree to XML file
* Handle XML attributes and special XML nodes like comments, processing instructions and CDATA sections
* Supports base64 encoding and decoding to allow handling embeded binary data
* Be studied, modified, customized, rewritten and used in other packages without any limitations. All code is included and documented. Software is distributed under BSD License (included).

This package can't:
* Guarantee to recover the same Matlab objects that were saved. If you need to be able to recover carbon copy of the structure that was saved than you will have to use one of the packages that uses special set of tags saved as xml attributes that help to guide the parsing of XML code. This package does not do that.
* Guarantee to work with MATLAB versions older than the package (2006/11). The code does not work with older versions of MATLAB.

Comments and Ratings (110)


JFz (view profile)

Hi, Thanks for this package. I believe it very useful. But when I try the xml_tutorial_example, I got this error:

Error using set
Parameter must be scalar.
Error in xml_io_tools.xmlwrite_xerces (line 48)

Why? Has anyone else encountered this error?

I am using R2016a.


Kevin Moerman

Zhe Wu

Zhe Wu (view profile)

1 1

1 1 (view profile)

very good

biao pan

Great submission.

Yayra Adugu

Very good and accurate. Only needed the xml write file

Great submission.

I just have a problem with outputing an array of values. It populates the array in a square bracket, which brings up an error. Is it possible to remove them using a Pref?


Aditya (view profile)

I create an array of structure elements and so each element needs the exact same format (i.e. fields) and so there are times when the fields are empty to indicate no entry. When writing to XML, it creates an empty element (e.g. <Empty/>). Is there a way to suppress this using preferences? My workaround is to output to a string, do string replacement and then write the string using fwrite to a file.

Was wondering if a preference for this would be useful to others as well?

I really like this submission - I've used it in multiple applications and it's awesome.


Aditya (view profile)

Really good submission. I use it a lot because working with structures is much easier than working directly with the DOM. Also the help documentation is very useful.

wu yiwen

Pref.XmlEngine = 'Xerces'; % use Xerces xml generator directly
xml_write('test.xml', MyTree, 'f_COLON_MyTree', Pref);

then there is a warning:
Warning: Possible deprecated use of set('Indenting','on') on Java boolean
property: use jobj.setIndenting(true) instead.

How should I correct this problem?thanks!



collin (view profile)

Should have included that Im using this tool to create an XML doc that can be saved as a KML doc to be opened in google earth

Great tool. I'm having an issue when trying to use this to make a Tour. Normal touring format is to create an gx:AnimateUpdate element, specify updates, then add a gx:Wait element immediately after it to allow time for updates. Unfortunately due to the recursive nature xml_write, the resulting xml lists all the gx:AnimateUpdate elements first, then it lists all the gx:Wait elements after, which is invalid for tours. Is there some use of flags that can alleviate this? I've poked around in the xml_write source code, but struggling. Thanks!


Leah (view profile)





Zaki (view profile)

Weihao Jiang

very useful!



Thanks Jaroslaw, a very good tool!

I'm just having some troubles with newline (\n) serialization in text elements.

I'd like to write an xml like:
<p>This is a multiline


root.p = sprintf('This is a multiline\ntext.');

xml_write('multilinetext.xml', root)

but the var2str function implementation substitute all chars < 32 with ' '.
Keeping char(10) i.e. LF should allow this king of textual content.

Is this tool still under maintenance? A fix on this topic would be very useful.

Thanks in advance


qiqi (view profile)

very good, but in my case, I get an OutOfMemoryError while dealing with 5.37m data. It seems too small


Yodit (view profile)

hi I am new to matlab, I was trying to chnage an xml file(which is too large it looks like this:
Result_Matrix =

[ 46686]
[ 4]
[1x2987899 char ]
[1x1 struct]

but I am interested in having the data [1x2987899 char ] part in (4x46686)matrix format. Can someone please explain how I can do that. Thank you in advance.


JY Su (view profile)

No doubt the best tool package ever!
However, is there any possibility to improve the speed of xml_write ?? It takes almost 200 sec to write a 50 mb xml file for me. Please help. Sincerely,


craq (view profile)

Excellent submission! I just managed to reproduce Mohinder's error (No static serializeXML method with appropriate signature exists in Java class com.mathworks.xml.XMLUtils). In my case it was caused by trying to run xmlwrite instead of xml_write.



Brilliant product, saved me a lot of time.

It create a really neat struct that is easy to navigate. And the gen_object_display.m script that shows the struct was invaluable when reading xml-files from other sources.

I had some issues with the error-reports (catch-statements)when using xml_read. Changing the debug varaible (line 89) to true removed the issue.


craq (view profile)

Fábio Nery


Marcin (view profile)

Abhijit Das

Abhijit Das


nan (view profile)

Works beautifully with several versions of Matlab; I really love the way it handles comments, too.

I wanted to suppress some of the terminal output, since I use large xml files and generally am only interested in small sections in any one program. There's an easy way to get around that, but since it took me awhile to find it, I'll share it:

t=evalc('[mystruct tree] = xml_read(cfgfile);');
if ~isempty(t)


Arash (view profile)

It is an amazing tool. I really appreciate your time to write such a great thing. It rocks man.

Just in case that can be useful for somebody else: I wanted to read my xml file as structure into MATLAB and then, change some data in that structure and finally, write back the structure into new xml file. But I had the problem and it was that the configuration of input xml file was different from output xml file configuration even if I didn't touch structure. What you should do to avoid this problem is doing following:

var = xml_read ('my_file.xml');

work with "var" and change whatever you want.

wPref.StructItem = false;
xml_write('my_file_new.xml', var, 'XXX',wPref);

I got "my_file_new.xml" with the same structure and configuration of "my_file.xml".


Arash (view profile)

It works great.
Thanks for the tool !


Joshua (view profile)


This xml_io_tool is very useful for me. But I have found some problems.

Here is a PVG810.xml. I read it and rewrite it again, the attributs of xml file is sorted alphabetically.

% MATLAB 2011B
% Read xml firstly.
[tree rootname domnode]= xml_read('PVG810.xml')

% Write xml again.
Pref.StructItem = 'false';
xml_write(tree, rootname, domnode,Pref.StructItem);

The initial:
<PVG810 BuildVersion = "1000"
TableVersion = "2000"
HeaderVersion = "1"
.... >

After writting:

<PVG810 ADCResolution = "18"
ADCTempOffset = "0"
ADCVref= "19"
BulidVersion = "1000"
.... >

How is happened. How can I take it?


Daniel (view profile)


I just noticed, that the xml_read function does not detect arrays correctly from attributes of xml-nodes.

I use the str2num=smart default option. I found, that there is an error in the str2var function on line 452 where I just removed the square brackets from the digit array:
digits = '(Inf)|(NaN)|(pi)|[\t\n\d\+\-\*\.ei EI\;\,]';

Now it works again like a charm. Great work by the way. Hope you can add the bugfix to a future release.


John Clayton


Thanks for this excellent work. I enjoy using it, so I wanted to share what I did to possibly improve "xml_read".

Reading in the following .xml file:
<?xml version="1.0" encoding="utf-8"?>

I performed the following commands:
>> D3=xml_read('testrdsmall_jec.xml');
>> D3

D3 =

xtr_base: '0x30010'
reg_base: '0x30000'
pcm_base: {'0x30040' '0x30050'}

It bothered me that the resulting data structure in Matlab has both xtr_base and reg_base the same. I tried using Pref.CellItem=true, as in the following commands:

>> Pref.CellItem=true;
>> D2=xml_read('testrdsmall_jec.xml',Pref);
>> D2

D2 =

xtr_base: {'0x30010'}
reg_base: '0x30000'
pcm_base: {{1x2 cell}}

This did produce a difference between xtr_base and reg_base, but the pcm_base was now a cell-array within a cell-array! So, I decided to make a modification to your code...

So now, with my small modification, I do the following commands:

>> D5=xml_read_jec('testrdsmall_jec.xml');
>> D5

D5 =

xtr_base: {'0x30010'}
reg_base: '0x30000'
pcm_base: {'0x30040' '0x30050'}

It produces the result I expect. However, when I use Pref.CellItem=true, I get:

>> D=xml_read_jec('testrdsmall_jec.xml',Pref);
>> D

D =

xtr_base: {'0x30010'}
reg_base: '0x30000'
pcm_base: {{1x2 cell}}

... which is probably not exactly as it should be. So, maybe my modification is not entirely correct.

What I did was to change lines 383-387 from this:
if (isfield(s,Pref.ItemName))
s.CONTENT = s.(Pref.ItemName);
s = rmfield(s,Pref.ItemName);
ItemContent = Pref.CellItem; % if CellItem than keep s.CONTENT as cells

to be this instead:
if (isfield(s,Pref.ItemName))
% Check for singleton nodes that have the special keyword to mark arrays,
% and keep them as cell arrays, even though the resulting cell array
% only has one member. -- Modification by John Clayton, 12/22/11.
if ~iscell(s.(Pref.ItemName))
s.CONTENT = s.(Pref.ItemName);
s = rmfield(s,Pref.ItemName);
ItemContent = true;
s.CONTENT = s.(Pref.ItemName);
s = rmfield(s,Pref.ItemName);
ItemContent = Pref.CellItem; % if CellItem then keep s.CONTENT as cells

What do you think of this change? Perhaps I did it not very well, but I wanted to tell you about it.

Thanks again for your excellent work!

- John Clayton

Edward Carney


Andrew (view profile)

Brilliant, just what I was looking for.

Good morning every one,
I get following error while using xmlwrite function. Can some one please suggest me where the rootcause lies?

xmlwrite(xmlFileName, theStruct)
??? Error using ==> javaMethod
No static serializeXML method with appropriate signature
exists in Java class com.mathworks.xml.XMLUtils


Reply to vaiadubai:
Creation of xml text is done within MATLAB xmlwrite or more precisely within java code called by xmlwrite. xmlwrite does not provide any parameters to customize the output, and java probably does not either. one possible solution is to open resulting file as text and perform global replace of 2 spaces with one.


I use this tool in a satisfactory way, I have this question.
When using (xml_write), I usually obtain this pattern with 2 spaces in the new line between the father node and the child node, like below:

Instead, I would like to obtain the pattern with 1 space less like below:

Where can I act to obtain the desired indentation?
Modifying the (xml_write), or the Matlab properties or setting
some attribute for the xml?

Thanks if you can help me!


Wei (view profile)


I am running the following example in the code

MyTree.MyNumber = 13;
MyTree.MyString = 'Hello World';
xml_write('test.xml', MyTree);
[tree treeName] = xml_read('test.xml');

But I got the following warning:

??? Warning: File: xml_read.m Line: 126 Column: 11 This try-catch syntax will continue to work in R2007a,
but may be illegal or may mean something different in future releases of MATLAB. See Release Notes for MATLAB Version 7.4, "Warning Generated by try-catch" for details.

The warning stopped the script and did not generate result for [tree treeName].

Any suggestions? Thanks!

Joao Henriques

Simple and works pretty well! The structures are a bit verbose but they're supposed to be parsed by my program anyway; any attempts to collapse some of the nested structures would only slow down the code (some similar submissions do this but are much slower). Thanks!

Julian E.C.

Thanks Jaroslaw. I worked before with other parsers, but none of them work as well as yours. It saved me lots of time.

Nikolay S.

Nikolay S. (view profile)

Thank you for this tool submitted. Unfortunately I'm receiving an error messages when trying to convert a class I've defined to an XML file(I'll need the opposite conversion as well). Is this tool designed to work with custom classes (assuming a conversion for the class will be defined) or this isn't the case, and the tool supports only Matlab native classes.

Than you Jarosalw, it's working

Reply to Bassem Hassan:

>> pref=[]; pref.NoCells=false;
>> tree=xml_read('test.xml',pref);
>> tree.Head1.Variable{1}
ans =
Type2d: []
ATTRIBUTE: [1x1 struct]

This is a great tool. It has greatly simplified my work, thank you

i have a smal problem here, may be one of you have an answer for it

if i have the following simple xml file
<Variable x="1" y="2">

<Variable x="3" y="4">
<Type3d z="20" />

<Variable x="5" y="6">


and i need to make a for loop to test the type for each variable type
(var1--> 2d var2-->3d var3 -->2d)

till now i cannot do that because the result when i access the variable 1 is

% matlab command window


ans =

Type2d: []
ATTRIBUTE: [1x1 struct]
Type3d: []
could any one help me

Thanks in advance

David Wagener

Saved me a lot of time. Very well documented and even some custom options. Thanks very much.


jaidev (view profile)

This question is regarding the capability of this tool to handle transfer function matrices.
Keep posting if there is a any update on how to save transfer function in xml file .

I have a variable named PF which looks like this :

Transfer function from input 1 to output...
#1: 1

#2: 0

Transfer function from input 2 to output...
#1: 0

#2: ---------
s + 0.215

??? Error using ==> char
Conversion to char from tf is not possible.

Error in ==> xml_write>var2str at 414
str = char(object);

Error in ==> xml_write>struct2DOMnode at 339
txt = xml.createTextNode(var2str(s, Pref.PreserveSpace));

Error in ==> xml_write>array2DOMnode at 366
struct2DOMnode(xml, parent, v, TagName, Pref ); % recursive call

Error in ==> xml_write>struct2DOMnode at 259
array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call

Error in ==> xml_write at 165
struct2DOMnode(DOMnode, root, tree, DPref.ItemName, DPref);

Error in ==> minky_xml_format_mat_file at 310
xml_write('test_jd.xml', aray_vec1);

There is a rare bug in str2val when using str2num. in case there is a string value which is a valid function name (for example 'eye'), it will be evaluated as a function (in this case it will return the number 1 instead of the string 'eye'). This happens in this code part:
elseif (~attribute) % see if it is a boolean 1D aray with no [] brackets
str1 = regexprep(str, 'false', '0', 'ignorecase');
str1 = regexprep(str1, 'true', '1', 'ignorecase');
num = str2num(str1); %#ok<ST2NM>
if(isnumeric(num) && numel(num)>0),
if all(num==0 | num==1), val = (num>0); end % save as logical
end % if convertion to a single was succesful than save

Reply to Christoph:
You can always perform your own matrix to string conversion, I am doing conversion equivalent to
but you can replace the first line and do some other conversion prior to writing. One thing you might not be able to do is to put a new line on the end of each row. It seems like MATLAB's xmlwrite (called by my xml_write) strips those.


I like this tool, because it gives me the matrix out of this xml:

<tensor dim1="3" dim2="6">
0 0 0 0 9.24234 0
0 0 0 9.24234 0 0
-9.03752 -9.03752 11.3172 0 0 0

but writing modifications of this matrix back to file, I get a matlab style matrix:

<tensor dim1="6" dim2="6">
<real>[121974000000 75494200000 73897300000 0 0 0; 75494200000 121974000000 73897300000 0 0 0; 73897300000 73897300000 104339000000 0 0 0; 0 0 0 21631600000 0 0; 0 0 0 0 21631600000 0; 0 0 0 0 0 23239900000]</real>

which I cannot process any further.
I tried all switches, but nothing changes.
Any help?

Reply to Peter Cotton:
Current library was never tested with sparse matrices, and I am actually surprised at its behavior, which I kind of like for most part. I will modify it so xml_read returns a sparse matrix.

Peter Cotton

Peter Cotton (view profile)

Can I suggest a small modification to xml_read so that sparse matrices are returned as sparse matrices rather than a string describing their construction (to be passed to eval)?

Reply to Bree:

Try reading with
Pref.Str2Num = 'always';

Default Str2Num preference is 'smart' which does not try to convert strings with more than 10k characters. Occasionally the strings in XML can be VERY large, for example when you have Base64 encoded images in the file. In such cases regexp code I am using can be very slow.


Bree (view profile)

Hi Jarowslaw,

I created an xml file contains of strings and numbers with your io_xml_tools and it works great, thanks alot.
But then I realized that the content of my *.xml file that I saved using xml_write function was changed after reading it through xml_read function. Some of the numbers are changed into characters.

For example: if I wrote
MyTree = [];
MyTree.Mynumber = 1:25000;
MyTree.Mystring = 'Thanks alot for sharing it';
xml_write('test.xml', MyTree)

after reading it through xml_read:
clear all;
The output will be:

MyTree =

Mynumber: [1x138895 char]
Mystring: 'Thanks alot for sharing it'

Where MyTree.Mynumber should be double, not char.

Is there anyway to fix it?


Naor Movshovitz

excellent, huge time saver.

Gus Lott

Seems to be an error when converting a large structure. What are the size limitations?

??? Index exceeds matrix dimensions.

Error in ==> xml_write>array2DOMnode at 369
if iscell(s), s = s{1}; end

Error in ==> xml_write>struct2DOMnode at 259
array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call

Error in ==> xml_write>struct2DOMnode at 305
struct2DOMnode(xml, node, x, field, Pref ); % recursive call
will modify 'node'

Error in ==> xml_write>array2DOMnode at 366
struct2DOMnode(xml, parent, v, TagName, Pref ); % recursive call

Error in ==> xml_write>struct2DOMnode at 271
array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call

Error in ==> xml_write>struct2DOMnode at 305
struct2DOMnode(xml, node, x, field, Pref ); % recursive call
will modify 'node'

Error in ==> xml_write at 165
struct2DOMnode(DOMnode, root, tree, DPref.ItemName, DPref);

Yuval Ben-Dov

Reply to 12 Jan 2010 message by Michael Glanznig: I am trying to be very cautious with str2num since it is based on matlab eval function and sometimes gives very unexpected results and I am using it to test is the string can be changed to a number. Try for example str2num('sphere').


Pete (view profile)

Very nice, top marks for usefulness and reliability. I now use xml files extensively, whereas before I would probably have had to rely on .mat files. Great job!

Unfortunately, due to a woeful bug in Matlab R2007a any lines of the form "catch ME" need to be removed for scripts such as xml_read to work, but I imagine that all of these scripts would all work like a charm right out of the box on any other - non-R2007a - system.

A great tool! I recently found a little glitch with number recognition.
When you have something like:
This is correctly identified as vector, however if you use
<tag attr="[1,2]">...</tag>
you get NaN as output.

In the str2var function it is distinguished between attribute and tag. If you have a tag the str2num function is used, which works. For an attribute the str2double function is used, which does not accept something in form of [1,2] as valid number.

Why are this two different functions used? Are there any side effects if you always use the str2num function?

Reply to 23 Oct 2009 message from Sebastiaan:
I will add PreserveSpace parameter for controlling empty string
handling while reading and writing

This is a great tool. It has greatly simplified my work.

However, I have discovered a small problem with xml_read(). The array of structures returned by xml_read() is organized differently depending on whether or not all structures have the same number of fields in the same order.

The code segment is
s(iItem).(field) = [x{:}];
if (Pref.NoCells)
s(iItem).(field) = forceCell2Struct(x);

This issue is that [x{:}] is equivalent to [x{1},x{2},...,x{n}] resulting in a [1xN] row vector. However, forceCell2Struct(x) uses the cell2struct() function which (for Matlab 7 R14 at least) results in a [Nx1] column vector.

The use of the cell2struct() function requires that the resulting output array must be arranged in a column. Accordingly, the above code segment is probably best "fixed" by transposing the row vector of the default array constructor into a column vector (e.g. = [x{:}]';).

Michael Murphy
Ford Motor Company

P.S. The xmlread() and xmlwrite() functions (for Matlab 7 R14 at least) cannot handle relative file specifications (i.e. ../file.xml) resulting in the ambiguous "Unable to parse XML file" error. To avoid this, the following code can be used to expand relative filepath specifications.

TERTIARY = @(expr,val1,val0) …
subsref( {val0,val1}, substruct( '{}', {1,1+sign(int32(expr))} ) );
ABS_PATH = @(file) …
strrep( fullfile( TERTIARY(strncmp(file,'.',1),pwd,''), file ), [filesep,'.',filesep], filesep );

[tree, root, node] = xml_read( ABS_PATH(filespec) );


Mark: have you tried using the Pref.Str2Num=false with xml_read?

Mark Weber


I am using your tool very often and I want to thank you for that.

This week I found a little problem and do not knwo how to solve. First of all my xml file:

Reading the first part is working, so I get a string called '00-11-88-87-F4-82' with the RSSI value. WIth the second part there is a problem. Because there are only numbers in the string, xmlread does not interpret it as a string. It calcluates the the value of -269. But I need it as String because it is not a number.
How can I solve the problem? Changing the name is not possible because it is given by the application where the xml is coming from.

Thank you in advance.

Kind regards

Mark Weber

Yuan Ren

I think there's some problem in this part:

digits = '[Inf,NaN,pi,\t,\n,\d,\+,\-,\*,\.,e,i, ,E,I,\[,\],\;,\,]';
s = regexprep(str, digits, ''); % remove all the digits and other allowed characters

I found this when one of my LeafNode called "IN" was recognized as "NaN".

I suggest the following modification.

>> regexprep('IN','[Inf,NaN]','')

ans =


>> regexprep('IN','(Inf)|(NaN)','')

ans =


One other thing is "num = str2num(str)" is a somewhat dangerous function. I'm not sure if it worth it to use this to provide some fancy functionality.


Hmm, having problems commenting. This is what the question used to be:

VERY nice tool indeed, especially the Pref settings which let you modify the output. However, I have a problem with empty tags or contents. My XML file has lines like this:

<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE PD>
<PD version="4.1">
<property value="Comments"> </property>

Which is read in Matlab as:
tree =
Misc: [1x1 struct]
EmptyTag: []
ATTRIBUTE: [1x1 struct] =
ATTRIBUTE: [1x1 struct]

So far, so good. However, on writing, the XML file is malformed:
<?xml version="1.0" encoding="UTF-8"?>
<PD version="4.1">
<property value="Comments"/>

I do not understand the DOM structure enough to try to find a cure for this. Also, setting tree.EmptyTag=' ' (one or more spaces) results in the same output.

How can this be corrected?


<property value="Comments"> </property>

Which is read in Matlab as:
tree =
Misc: [1x1 struct]
EmptyTag: []
ATTRIBUTE: [1x1 struct] =
ATTRIBUTE: [1x1 struct]

So far, so good. However, on writing, the XML file is malformed:
<?xml version="1.0" encoding="UTF-8"?>
<PD version="4.1">
<property value="Comments"/>

I do not understand the DOM structure enough to try to find a cure for this. Also, setting tree.EmptyTag=' ' (one or more spaces) results in the same output.

How can this be corrected?

Ok, it is amazing how fast bright ideas come after posting a problem.

I noticed that setting:
set(objOutputFormat, 'PreserveSpace', 'on')
in xmlwrite_xerces.m ~ line 48 deals with the problem and outputs a genuine XML file.

Unfortunately, the layout is unreadable (for larger xml files) to the eye:
<PD version="4.1"><Misc><property value="Comments"></property></Misc><EmptyTag></EmptyTag></PD>

John Perko

I get an error with multiple preferences--if Pref structure contains both StructItem='false' and CellItem='false'

Reply to Val Schmidt Comments:

By default xml_read is configured for most common use. If you need performance, DOMnode2struct can be sometimes significantly speeded up if you use Pref.Str2Num='never' and/or trim your output by changing Pref.ReadAttr, Pref.ReadSpec and Pref.NumLevels.

Val Schmidt

Val Schmidt (view profile)

This package works well for us - reading xml that fails under other xml packages.

However it is EXTREMELY slow (for me).

In parsing a 976K xml file with a parent function that calls xml_read(), I find in profiling that "xml_read>DOMnode2struct" consumes 206 seconds of the total 210.

It appears that the process of unwrapping the results of the DOM object into the matlab structure is what kills it. Oddly, my cpu is rarely maxed out, which seems to indicate some memory management bottleneck.

Is there any chance this is fixable?


I work with these functions all the time. You did a megnificent job.
I have a sugesttion for improvment: The fact that the item notaion works only for structs that are arrays of size larger than 1 creates xml-files with different hierarchy depending on the structure size. When some other program needs to read this xml it becomes a problematic issue.
So... I suggest that you add a preferance entry that forces item notation even for structs of length 1.

Thanks a lot for this submition & keep up the good work.

Thanks Jaroslaw! Works like a charm!

Even though xml_read.m does a check to pass ver >=7.1, the ME in catch ME (as pointed out by Ryan Sharp on 5May2009) fails for 7.1. I commented out the ME and also removed getReport() call, which is not on standard path for 7.1. Seems to work with these edits, but maybe there is some unintended side effect?

Daniel Lyddy


I am guessing that your new base64 instructions work perfectly for the case you decribe in the documentation, but in my case, I have an image already stored as a two-dimensional MATLAB uint8 array. Peter Acklam's base64encode only seems to work with vector data of dimension one, so here is what I had to do to get things to work. Assume 'img' is a 2D array of uint8 that already exists in MATLAB's workspace.

[imgHeight, imgWidth] = size(img);
MyTree.MyImage.height = imgHeight;
MyTree.MyImage.width = imgWidth; = 'base64'; = base64encode(img(:));
xml_write(MyTree, 'testImage.xml');
tree = xml_read('testImage.xml');
newImg = uint8(reshape(base64decode(, [tree.MyImage.height, tree.MyImage.width]));

When I do this, newImg matches img pixel-for-pixel.



Daniel Lyddy

Does anyone know how to use the base64 encoding features in xml_write? I have downloaded and installed Peter J. Acklam's toolbox, but I don't see anything in the documentation, and I can't find any calls to 'base64encode' in the xml_write.m file.

Ryan Sharp

I would love to try this, but it appears to not work correctly with matlab 7.4?
I noticed there are 'catch ME' statements, which I think were not introduced yet in 7.4?

Works really nice... exactly what I wanted!!


Peter (view profile)

Very helpful - what a perfect tool!

This worked perfectly. Every detail is exactly the way I needed it. Thanks!


Yan (view profile)

Thanks for the great work!


This is a great tool, but I'm having a problem. I'm trying to use it to save/load figure style structures. The problem is that the style structures include many empty strings. xml_write saves these as empty tags. When xml_read load the xml, empty tags are converted to empty matrices.

Ie. if I save an empty string ('') to xml, and load, I get an empty matrix ([]). This makes , e.g.

xml_write('figstyle.xml', figstyle);
figstyle_from_xml = xml_read('figstyle.xml')

complain. However, converting all empty matrices to empty strings when loading would not work, since some of the struct members _should_ be empty matrices.

I hope this could easily be fixed :)



Mike (view profile)



Tracy (view profile)

sorry - i used the wrong function. But when i use teh right one i get this error

>> xmlwrite_xerces(xx)
51 objFile =;
??? No constructor '' with matching signature found.

Error in ==> xmlwrite_xerces at 51
objFile =;


Tracy (view profile)

I get different results when i write to a file and when i write to a buffer.

>> MyTree

MyTree =

MyNumber: 13
MyString: 'Hello World'

when writing to the buffer my CDATA is not correct.

xx=xml_write([], MyTree, {'MyTree', [], 'This is a global comment'}, Pref);


ans =

<?xml version="1.0" encoding="utf-8"?><!--This is a global comment-->
<MyString>Hello World</MyString>

when writing to a file it is

>> xml_write('xx.xml', MyTree, {'MyTree', [], 'This is a global comment'}, Pref);
>> type ('xx.xml')

<?xml version="1.0" encoding="UTF-8"?>
<!--This is a global comment-->
<MyString>Hello World</MyString>

am i doing something wrong??

Andrej Mosat

Parsing my cell 'a' containing mixed types :
>> size(a)
ans =
134 12
>> a(1,:)
ans =
[501][-1153850764] 'Cartridge-1' [9] [11] [0] [1] [-1] [1] [0] 'Filter - In-Line' 'none'

>> xml_write ...
results in:
<?xml version="1.0" encoding="utf-8"?>
and finish.

No support for heterogeneous cells? If you added this, you`d have 200% boost in the downloads.
I know it`s not that hard parsing each element of the variable to be saved. Matlab does not have other way of saving complex data than .mat files, which is kind of scary if you want to save & use in another programming language. For now, I have to look for other solution. At the end, copy&paste some 17 structures with 8 subfields will take shorter than trying things here.
Just do it, please ;-)

John Reego

Works great. We have tested with structures that are as large as 6 megabytes with tens of thousands of variables. Takes a couple of seconds to transfer - but everything works.

Mark Neil

Need some help understanding how to properly use this to store/restore matrices.

I see mostly positive reviews, so I'm really hoping I'm just doing something wrong (as matrices are somewhat common in MATLAB).

Consider the following code...

a.Val = 10;
a.OneByThree = [0 0 0];
a.ThreeByOne = [0; 0; 0];
xml_write('a.xml', a);
b = xml_read(a.xml');

You get an XML file which looks like this...

<?xml version="1.0" encoding="utf-8"?>
<OneByThree>0 0 0</OneByThree>
<ThreeByOne>0 0 0</ThreeByOne>

And output which looks (compressed) like this...

ans = double
ans = double
ans = double
Val: [10]
OneByThree: [0 0 0]
ThreeByOne: [3x1 double]
ans = double
ans = char
ans = char
Val: [10]
OneByThree: '0 0 0'
ThreeByOne: '0 0 0'

Two issues...

1) Your double matrices aren't double anymore, they are character arrays.
2) No preservation of the dimensionality of the matrices.

Is there a solution to this? Some flag I'm not using correctly (although I tried several).

Thanks in advance,


taba taba

very good

Hugo Costelha

Nice work ;)

In line 286 of xml_read.m, I added an "if (Pref.Str2Num)", to honor the preferences.

Eduard Rudyk

Excellent tool. Thanks.

Martin Bergtholdt

Nice work!

shlomi israel

Works well and excelently documented.

Nick Rhee

I am getting an error "Unable to parse XML file " from xml_read. Would appreciate your help!

Jeff Kirschner

Hi, apologies if this is the wrong place for this, but xml_read is giving me this error:

xml_read.m Line: 132 Column: 13
"]" expected, "identifier" found.

Would anyone happen to have a solution for this pls? Thanks in advance.
I'm using Matlab 6.5 R13

Jennifer Cooper

Does exactly what I needed and the preferences options already cover the options I'm likely to need!

Anna Kelbert

Great routines; exactly what I need and very easy to use, no knowledge of Java or DOM needed. They create a wonderful link between Matlab structures and *.xml files. Unfortunately, there is a tiny bug in the xml_write routine: the attributes of the root node (i.e. xmlns and schema location) are not written (although they are saved as attributes by xml_read). Preferences to allow for custom style for writing real values would also help, but the default is reasonable.

Stephen Morris

This did exactly what I wanted - actually, what I'd originally hoped that the native Matlab functions would do! Very easy to use; saved me no end of time crafting similar routines for myself.



Fix problem with empty cells reported by Richard Cotton; fixed issues with reading boolean arrays reported by Zohar Bar-Yehuda; Improved speed of base64 coding and decoding by switching to java based code.

Fixed problem with writing 1D arrays and 2D cell arrays. Extended Pref.Num2Str to: never, smart and always. Added parameter Pref.KeepNS for keeping or ignoring namespace data.

Fixed problem reported by Anna Krewet of converting dates in format '2007-01-01' to numbers. Improved and added warning messages. Added detection of old Matlab versions incompatible with the library. Expanded documentation.

Added tutorial "Published M-file", few minor code changes adding more customization parameters

Fixed problem reported by Anna Kelbert in Reviews. Also: added support for Processing Instructions, added support for global text nodes: Processing Instructons and Comments, allowed writing tag names with special characters

Fix by Alberto Amaro of xml_write to allow writing CDATA sections.

Made changes to allow handling special node types like CDATA_SECTIONs and COMMENTs.

MATLAB Release
MATLAB 7.10 (R2010a)

Inspired: xunit4

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video