matlab 编辑 xml 文件添加标签

matlab edit xml file add tag

我有文件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>

我想加载这个文件并添加一个标签,例如

<D>this is the sample</D>

标签A之后B之前,怎么处理? 谢谢

如果你想读取输入文件并用"added"字符串写入一个新的“.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);

希望对您有所帮助。