我有文件exp.xml
public static void testScript() {
String line;
try {
String[] cmd = {"/bin/sh", "-c", "queue-tool -h"};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader in =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = in.readLine()) != null) { //line is null so nothing to read
System.out.println(line);
}
in.close();
} catch (InterruptedException iEX) {
iEX.printStackTrace();
} catch (IOException ioEX) {
ioEX.printStackTrace();
}
}
我想加载此文件并添加像
这样的标记<?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>
标签A之后和B之前,如何处理?
谢谢
答案 0 :(得分:2)
如果你想阅读输入文件并写一个新的&#34; .xml&#34;添加&#34;添加&#34;字符串,你可以试试这个:
% 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);
希望这有帮助。