我有两个 XML 文件,我想使用 java 将它们合并到最后一个 XML 文件中。
File1的格式:
<root>
<a>
<a>--include two lines under <a>
<c/>
</a>
<d/>
</root>
File2的格式:
<root>
<a>
<c/>
</a>
<d/> -- include 1 more line at the last
</root>
谁能告诉我在两个文件中添加特定信息后如何合并这些文件。
这是我尝试过的,但它并没有解决我的目的..
public class Xml {
public static void main(String[] args) throws Exception {
Writer output = null;
output = new BufferedWriter(new FileWriter("H:\\merged_xml.xml"));
String newline = System.getProperty("line.separator");
output.write("<a>");
// Read in xml file 1
FileInputStream in = new FileInputStream("file1.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.contains("<a>")){
strLine = strLine.replace("<a>", "info to include");
}
if (strLine.contains("</a>")){
strLine = strLine.replace("</a>", "info to include");
}
output.write(newline);
output.write(strLine);
System.out.println(strLine);
}
// Read in xml file 2
FileInputStream in2 = new FileInputStream("file2.xml");
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String strLine2;
while ((strLine2 = br2.readLine()) != null) {
if (strLine2.contains("<d>")){
strLine2 = strLine2.replace("<d>", "info to include");
}
output.write(strLine2);
output.write(newline);
System.out.println(strLine2);
}
output.write("</d>");
output.close();
System.out.println("Merge Complete");
}
}