我想读取一个 XML 文件并修改一些字符串,保存然后用 MATLAB 关闭该文件。到目前为止我已经:
f = fopen( 'output_results\results.xml', 'w' );
我需要在文件的 optList
节点中添加以下行(见下文):
<opt name="*_option1">true</opt>
<opt name="format">
<f1>file:/C:/working/types.h</f1>
</opt>
保存然后关闭文件
fclose(f);
如何在 XML 文件中添加上述行?
文件内容:
<?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>
最佳答案
发现here ,不可能打开文件、查找位置、在其中添加内容,同时保留其余文本,然后关闭。
您只需重写整个文件即可解决此问题:
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');
如果这确实是一个一次性问题,那么上面的技巧就可以了。但是,正如 @bdecaf 所建议的,您应该使用正确的工具来完成这项工作。我建议完全在 MATLAB 之外进行编写(以避免代码过于复杂),并且只需通过 MATLAB 的系统调用语法调用外部工具/库(输入 help !
)。
关于xml - MATLAB:修改XML文件并保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11983815/