如果您想读取输入文件并使用“添加”字符串编写一个新的“.xml”文件,您可以试试这个:
% Open input file
fp=fopen('a.xml','rt');
% Open new output file
fp_out=fopen('new_file.xml','wt');
% Define the reference tag
ref_tag='<A';
% Define the line to be added
str_to_add=' <D>this is the sample</D>';
% Read the input file
tline = fgets(fp);
while ischar(tline)
% Get the current tag
[curr_tag,str]=strtok(tline);
% If the reference tag is found, add the new line
if(strcmp(curr_tag,ref_tag))
fprintf(fp_out,'%s%s\n',tline,str_to_add);
% Else print the line
else
fprintf(fp_out,'%s',tline);
end
% Read the next input line
tline = fgets(fp);
end
% Close the input file
fclose(fp);
% Close the output file
fclose(fp_out);
否则,如果要将输入文件导入 MatLab 工作区并添加新行,则可以将其存储在 cellarray 中:
% Open input file
fp=fopen('a.xml','rt');
% Define the reference tag
ref_tag='<A';
% Define the line to be added
str_to_add=' <D>this is the sample</D>';
% Read the input file
cnt=1;
tline = fgets(fp);
while ischar(tline)
% Get the current tag
[curr_tag,str]=strtok(tline);
% If the reference tag is found, add the new line
if(strcmp(curr_tag,ref_tag))
C(cnt)=cellstr(tline);
cnt=cnt+1;
C(cnt)=cellstr(str_to_add);
cnt=cnt+1;
% Else print the line
else
C(cnt)=cellstr(tline);
cnt=cnt+1;
end
% Read the next input line
tline = fgets(fp);
end
% Close the input file
fclose(fp);
希望这会有所帮助。