我有兩個我想要使用java合併的XML文件,最後是一個XML文件。在Java中合併兩個XML文件並且還添加額外信息
文件1的格式:
<root>
<a>
<a>--include two lines under <a>
<c/>
</a>
<d/>
</root>
文件2的格式:
<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");
}
}
嘗試檢查此帖討論了類似的問題 - http://stackoverflow.com/questions/648471/merge-two-xml-files-in-java – Prashanth 2012-04-10 11:20:45
@Sonu:謝謝你..!但是,如何使用分隔符來避免編寫不需要的元素? – dmurali 2012-04-10 11:24:05
對不起,沒有得到你的意思。你能舉一個小例子嗎? – Prashanth 2012-04-10 11:29:34