【问题标题】:matlab edit xml file add tagmatlab编辑xml文件添加标签
【发布时间】:2015-06-15 16:10:59
【问题描述】:

我有文件 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之前,怎么处理? 谢谢

【问题讨论】:

    标签: xml matlab tags


    【解决方案1】:

    如果您想读取输入文件并使用“添加”字符串编写一个新的“.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);
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      相关资源
      最近更新 更多