lola
lola

Reputation: 5789

MATLAB: modify XML file and save

I would like to read an XML file and modify some strings, save then close the file with MATLAB. So far I have:

f = fopen( 'output_results\results.xml', 'w' ); 

I need to add the following line inside the optList node of the file (see below):

<opt name="*_option1">true</opt>
<opt name="format">
    <f1>file:/C:/working/types.h</f1>
</opt>

save then close the file

fclose(f); 

How can I add the above lines in an XML file?

File content:

<?xml version="1.0" encoding="utf-8"?> 
<Custom_project name="" val="True" name="file1" path="file:/C:/Users/Local/Temp/info.xml" version="1.0">
<verif="true" name="values" path="file:/C:/Users/Temp/folder1">
    <optList name="values">
        <opt name="color">red</opt>
        <opt name="police">calibri</opt>
        <opt name="font">blue</opt>
    </optList>
</verif>
<toto="myvalue" name="option1">
    <opt name="myvalue_1">32</opt>
    <opt name="-total">All</opt> 
    <opt name="characteristic">hybrid</opt>
</toto> 

Upvotes: 2

Views: 5843

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

As found here, it's not possible to open a file, seek a location, add stuff there, while preserving the rest of the text, and close.

You can work around this simply by re-writing the entire file:

f = fopen( 'output_results\results.xml', 'r' ); 
g = fopen( 'output_results\results.xml.TEMP', 'w' ); 

while ~feof(f)
    line = fgets(f);
    fprintf(g, '%s', line);
    if strcmpi(line, '<optList name="values">')
        fprintf(g, '%s\n%s\n%s\n%s\n',....
            '<opt name="*_option1">true</option>',...
            '<opt name="format">',...
            '<f1>file:/C:/working/types.h',...
            '</f1></option>');
    end
end

fclose(f), fclose(g);
movefile('output_results\results.xml.TEMP', 'output_results\results.xml');

If this is really a one-off problem, the hack above is OK. But, as suggested by @bdecaf, you should use the proper tool for the job. I'd suggest to do the writing entirely outside of MATLAB (to avoid overly complex code), and just call an external tool/library via MATLAB's system call syntax (type help !).

Upvotes: 1

bdecaf
bdecaf

Reputation: 4732

In your example you never read the file.

But for XML you can save a lot of troubles if you use the java XML tools. You an call them directly from Matlab.

Upvotes: 1

Related Questions