Reputation: 293
I have two XML files which I would like to merge using java, into one XML file at the end.
Format of File1:
<root>
<a>
<a>--include two lines under <a>
<c/>
</a>
<d/>
</root>
Format of File2:
<root>
<a>
<c/>
</a>
<d/> -- include 1 more line at the last
</root>
Can anybody tell me how do i merge these files after adding specific information in both the files.
And this is what I have tried, but it doesn't solve my purpose..
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");
}
}
Upvotes: 1
Views: 932
Reputation: 1398
You need to use an XML parser to achieve what you want- no need to use Java IO classes for reading and writing to a new file. You can use a streaming XML parser (google for 'java StAX'). If you use the javax.xml.stream library you'll find that the XMLEventWriter has a convenient method XMLEventWriter#add(XMLEvent). All you have to do is loop over the top level elements in each document and add them to your writer using this method to generate your merged result. The only funky part is implementing the reader logic that only considers (only calls 'add') on the top level nodes.
Upvotes: 1