Merging two XML files into one XML file using Java
Posted
by
dmurali
on Stack Overflow
See other posts from Stack Overflow
or by dmurali
Published on 2012-04-11T17:20:01Z
Indexed on
2012/04/11
17:29 UTC
Read the original article
Hit count: 451
I am stuck with how to proceed with combining two different XML files(which has the same structure). When I was doing some research on it, people say that XML parsers like DOM or StAX will have to be used. But cant I do it with the regular IOStream? I am currently trying to do with the help of IOStream but this is not solving my purpose, its being more complex.
For example, What I have tried is;
public class GUI {
public static void main(String[] args) throws Exception {
// Creates file to write to
Writer output = null;
output = new BufferedWriter(new FileWriter("C:\\merged.xml"));
String newline = System.getProperty("line.separator");
output.write("");
// Read in xml file 1
FileInputStream in = new FileInputStream("C:\\1.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.contains("<MemoryDump>")){
strLine = strLine.replace("<MemoryDump>", "xmlns:xsi");
}
if (strLine.contains("</MemoryDump>")){
strLine = strLine.replace("</MemoryDump>", "xmlns:xsd");
}
output.write(newline);
output.write(strLine);
System.out.println(strLine);
}
// Read in xml file 2
FileInputStream in = new FileInputStream("C:\\2.xml");
BufferedReader br1 = new BufferedReader(new InputStreamReader(in));
String strLine1;
while ((strLine1 = br1.readLine()) != null) {
if (strLine1.contains("<MemoryDump>")){
strLine1 = strLine1.replace("<MemoryDump>", "");
}
if (strLine1.contains("</MemoryDump>")){
strLine1 = strLine1.replace("</MemoryDump>", "");
}
output.write(newline);
output.write(strLine1);
I request you to kindly let me know how do I proceed with merging two XML files by adding additional content as well. It would be great if you could provide me some example links as well..!
Thank You in Advance..! System.out.println(strLine1); }
}
© Stack Overflow or respective owner