Reputation: 63
I have file exp.xml
<?xml version="1.0" encoding="utf-8"?>
<A ID="1" nbr="5">
<B nom="1_1.mat"/>
<C dist12="msk2" />
<C dist13="msk3" />
<C dist14="msk4" />
</A>
I want to load this file and add a tag like
<D>this is the sample</D>
after the tag A and before B, how to deal? Thank you
Upvotes: 0
Views: 78
Reputation: 5190
If you want to read the input file and write a new ".xml" file with the "added" string, you can try this:
% 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);
Otherwise, if you want to import the imput file into MatLab workspace and add the new line, you can store it in a 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);
Hope this helps.
Upvotes: 2