您可以将 XML 视为文本文件并将它们组合起来。与其他方法相比,这非常快。请看下面的代码:-
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class XmlComb {
static Set<String> lstheader = new HashSet<String>();
public static void main(String[] args) throws IOException {
Map<String,List<String>> map1 = getMapXml("J:\\Users\\Documents\\XMLCombiner01\\src\\main\\resources\\File1.xml");
Map<String,List<String>> map2 = getMapXml("J:\\Users\\Documents\\XMLCombiner01\\src\\main\\resources\\File2.xml");
Map<String,List<String>> mapCombined = combineXML(map1, map2);
lstheader.forEach( lst -> {
System.out.println(lst);
});
try {
mapCombined.forEach((k,v) -> {
System.out.println(k);
v.forEach(val -> System.out.println(val));
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Map<String,List<String>> combineXML(Map<String, List<String>> map1, Map<String, List<String>> map2 ) {
Map<String,List<String>> map2Modified = new TreeMap<String, List<String>>();
Map<String,List<String>> mapCombined = new TreeMap<String, List<String>>();
// --- Modifying map ---
for(String strKey2 : map2.keySet()) {
if(map1.containsKey(strKey2)) {
map2Modified.put(strKey2.split("\">")[0] + "_1\">", map2.get(strKey2));
}
else {
map2Modified.put(strKey2 , map2.get(strKey2));
}
}
//---- Combining map ---
map1.putAll(map2Modified);
return map1;
}
public static Map<String,List<String>> getMapXml(String strFilePath) throws IOException{
File file = new File(strFilePath);
BufferedReader br = new BufferedReader(new FileReader(file));
Map<String, List<String>> testMap = new TreeMap<String, List<String>>();
List<String> lst = null;
String st;
String strCatalogName = null;
while ((st = br.readLine()) != null) {
//System.out.println(st);
if(st.toString().contains("<TestCase")){
lst = new ArrayList<String>();
strCatalogName = st;
testMap.put(strCatalogName, lst);
}
else if(st.contains("</TestCase")){
lst.add(st);
testMap.put(strCatalogName,lst);
}
else {
if(lst != null){
lst.add(st);
}else {
lstheader.add(st);
}
}
}
return testMap;
}
}