Code covered by the BSD License  

Highlights from
xml_io_tools

4.85714

4.9 | 54 ratings Rate this file 156 Downloads (last 30 days) File Size: 216 KB File ID: #12907

xml_io_tools

by

 

06 Nov 2006 (Updated )

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

| Watch this File

File Information
Description

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.

Acknowledgements

This file inspired Xunit4.

MATLAB release MATLAB 7.10 (R2010a)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (85)
22 Jul 2014 Yodit

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]
'f'
[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.

06 Feb 2014 JY Su

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,

31 Jan 2014 craq

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.

16 Aug 2013 Matthew

AWESOME!!

13 Aug 2013 Anders Bergåker

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.

05 Aug 2013 craq  
02 Aug 2013 Fábio Nery  
07 Dec 2012 Marcin  
13 Nov 2012 Abhijit Das  
13 Nov 2012 Abhijit Das  
11 Sep 2012 nan

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)
disp(t);
end

07 Sep 2012 Arash

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".

07 Sep 2012 Arash  
10 May 2012 Gerard Sanromà

It works great.
Thanks for the tool !

24 Apr 2012 Zohar Bar-Yehuda  
11 Mar 2012 Joshua

Jaroslaw,

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?

02 Jan 2012 Daniel

Hej,

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.

Daniel

22 Dec 2011 John Clayton

Jaroslaw,

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"?>
<ROOT>
<xtr_base>
<item>0x30010</item>
</xtr_base>
<reg_base>0x30000</reg_base>
<pcm_base>
<item>0x30040</item>
<item>0x30050</item>
</pcm_base>
</ROOT>

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
end

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;
else
s.CONTENT = s.(Pref.ItemName);
s = rmfield(s,Pref.ItemName);
ItemContent = Pref.CellItem; % if CellItem then keep s.CONTENT as cells
end
end

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

14 Dec 2011 Edward Carney  
23 Sep 2011 Antoan Nikolaev  
10 Aug 2011 Andrew

Brilliant, just what I was looking for.

06 Jun 2011 Mohinder Pandey

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

Thanks

06 May 2011 Jaroslaw Tuszynski

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.

06 May 2011 vaiadubai

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:
<father>
<child>

Instead, I would like to obtain the pattern with 1 space less like below:
<father>
<child>

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!

16 Mar 2011 Wei

Hi,

I am running the following example in the code

MyTree=[];
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!

05 Mar 2011 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!

04 Mar 2011 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.

07 Feb 2011 Nikolay S.

Hi.
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.
Thanks!

05 Nov 2010 Bassem Hassan

Than you Jarosalw, it's working

04 Nov 2010 Jaroslaw Tuszynski

Reply to Bassem Hassan:

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

04 Nov 2010 Bassem Hassan

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
<Head0>
<Head1>
<Variable x="1" y="2">
<Type2d/>
</Variable>

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

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

</Head1>
</Head0>

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

tree=xml_read(very_simple.xml')
tree.Head1.Variable(1)

ans =

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

Thanks in advance

27 Oct 2010 David Wagener

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

13 Oct 2010 jaidev

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 :
PF

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

#2: 0

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

0.215
#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);

04 Oct 2010 Zohar Bar-Yehuda

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
end

16 Sep 2010 Jaroslaw Tuszynski

Reply to Christoph:
You can always perform your own matrix to string conversion, I am doing conversion equivalent to
X.linear.tensor.real=mat2str(X.linear.tensor.real);
xml_write('test.xml',X);
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.

16 Sep 2010 Christoph

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

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

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

<linear>
<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>
</tensor>
</linear>

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

08 Sep 2010 Jaroslaw Tuszynski

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.

07 Sep 2010 Peter Cotton

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)?

01 Sep 2010 Jaroslaw Tuszynski

Reply to Bree:

Try reading with
Pref.Str2Num = 'always';
MyTree1=xml_read('test.xml',Pref);

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.

31 Aug 2010 Bree

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;
MyTree=xml_read('test.xml')
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?

best,
-Bree

30 Aug 2010 Naor Movshovitz

excellent, huge time saver.

30 Aug 2010 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);

20 May 2010 Yuval Ben-Dov  
04 May 2010 Jaroslaw Tuszynski

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').

16 Mar 2010 Pete

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.

12 Jan 2010 Michael Glanznig

A great tool! I recently found a little glitch with number recognition.
When you have something like:
<tag>[1,2]</tag>
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?

03 Dec 2009 Jaroslaw Tuszynski

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

30 Nov 2009 Michael Murphy

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
try
s(iItem).(field) = [x{:}];
catch
if (Pref.NoCells)
s(iItem).(field) = forceCell2Struct(x);
end
end

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) );

04 Nov 2009 Sebastiaan

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

02 Nov 2009 Mark Weber

Hi,

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:
<measurement>
<values>
<value>
<rssi>-90</rssi>
<identifier>
<name>00-11-88-87-F4-82</name>
</identifier>
</value>
</values>
</measurement>
<measurement>
<values>
<value>
<rssi>-81</rssi>
<identifier>
<name>00-11-88-88-42-40</name>
</identifier>
</value>
</values>
</measurement>

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

31 Oct 2009 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 =

IN

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.

23 Oct 2009 Sebastiaan

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">
<Misc>
<property value="Comments"> </property>
</Misc>
<EmptyTag>
</EmptyTag>
</PD>

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

tree.Misc.property =
CONTENT: []
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">
<Misc>
<property value="Comments"/>
</Misc>
<EmptyTag/>
</PD>

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?

23 Oct 2009 Sebastiaan

<Misc>
<property value="Comments"> </property>
</Misc>
<EmptyTag>
</EmptyTag>
</PD>

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

tree.Misc.property =
CONTENT: []
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">
<Misc>
<property value="Comments"/>
</Misc>
<EmptyTag/>
</PD>

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?

EDIT
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>

06 Aug 2009 John Perko

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

22 Jun 2009 Jaroslaw Tuszynski

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.

21 Jun 2009 Val Schmidt

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?

19 Jun 2009 Shlomi

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.

02 Jun 2009 Arpad Andrassy

Thanks Jaroslaw! Works like a charm!

19 May 2009 Thomas Pilutti

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?

15 May 2009 Daniel Lyddy

Jarek:

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;
MyTree.MyImage.data.ATTRIBUTE.EncodingMIMEType = 'base64';
MyTree.MyImage.data.CONTENT = base64encode(img(:));
xml_write(MyTree, 'testImage.xml');
tree = xml_read('testImage.xml');
newImg = uint8(reshape(base64decode(tree.MyImage.data.CONTENT), [tree.MyImage.height, tree.MyImage.width]));

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

Thanks,
Daniel

Daniel

14 May 2009 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.

05 May 2009 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?

05 May 2009 Leonardo Glavina

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

29 Apr 2009 Peter

Very helpful - what a perfect tool!

12 Mar 2009 Michael Heistand

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

12 Mar 2009 Michael Heistand  
25 Feb 2009 Yan

Thanks for the great work!

03 Feb 2009 Neilen Marais

Hi,

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')
set(gcf,figstyle_from_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 :)

Thanks
Neilen

05 Jan 2009 Armel Mevellec  
18 Nov 2008 Mike

perfect

10 Nov 2008 Tracy

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

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

Error in ==> xmlwrite_xerces at 51
objFile = java.io.File(result);

10 Nov 2008 Tracy

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

>> MyTree

MyTree =

CDATA_SECTION: '<A>txt</A>'
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);

xmlwrite(xx)

ans =

<?xml version="1.0" encoding="utf-8"?><!--This is a global comment-->
<MyTree>&lt;A&gt;txt&lt;/A&gt;<MyNumber>13</MyNumber>
<MyString>Hello World</MyString>
</MyTree>

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-->
<MyTree><![CDATA[<A>txt</A>]]><MyNumber>13</MyNumber>
<MyString>Hello World</MyString>
</MyTree>

am i doing something wrong??

30 May 2008 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"?>
<a>
<item>501</item>
<item>502</item>
<item>503</item>
...
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 ;-)

30 Apr 2008 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.

06 Mar 2008 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];
class(a.Val)
class(a.OneByThree)
class(a.ThreeByOne)
gen_object_display(a)
xml_write('a.xml', a);
b = xml_read(a.xml');
class(b.Val)
class(b.OneByThree)
class(b.ThreeByOne)
gen_object_display(b)

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

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

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,

Mark

05 Feb 2008 taba taba

very good

02 Jan 2008 Hugo Costelha

Nice work ;)

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

12 Dec 2007 Eduard Rudyk

Excellent tool. Thanks.

24 Oct 2007 Martin Bergtholdt

Nice work!

27 Sep 2007 shlomi israel

Works well and excelently documented.

19 Jul 2007 Nick Rhee

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

27 Jun 2007 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

08 Jun 2007 Jennifer Cooper

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

30 May 2007 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.

06 Dec 2006 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.

Updates
24 Jan 2007

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

12 Mar 2007

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

21 Jun 2007

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

20 Jul 2007

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

23 Jan 2008

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.

23 Jun 2008

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.

05 Nov 2010

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.

Contact us