private Map<String, Element> removeDuplication(String filepath1, String filepath2, String rootName, String attrName) throws Exception {
// 读取第一个xml
Map<String, Element> map1 = readXml(filepath1, rootName, attrName);
Set<String> set1 = map1.keySet();
System.out.println(map1.keySet());
// 读取第二个xml
Map<String, Element> map2 = readXml(filepath2, rootName, attrName);
Set<String> set2 = map2.keySet();
System.out.println(map2.keySet());
Map<String, Element> newMap = new TreeMap<>();
// 第二个map根据第一个去重
Sets.SetView<String> difference = Sets.difference(set2, set1);
for (String s : difference) {
newMap.put(s, map2.get(s));
}
return newMap;
}
private void writeXml(Map<String, Element> map, String filepath, String rootName) throws Exception {
// 重写文件
// 1. 创建Docuembnt
Document doc = DocumentHelper.createDocument();
// 2. 创建根元素
Element root = doc.addElement(rootName);
// root.addComment("文档的根city已经创建。");// 添加注释
for (Map.Entry<String, Element> entry : map.entrySet()) {
entry.getValue().setParent(null);
root.add(entry.getValue());
// entry.getValue().setParent(root);
// doc.add(entry.getValue());
}
// 创建输出流
Writer out = new PrintWriter(filepath, "utf-8");
// 格式化
OutputFormat format = new OutputFormat(" ", true);
format.setTrimText(true);//去掉原来的空白(\t和换行和空格)!
XMLWriter writer = new XMLWriter(out, format);
// 把document对象写到out流中。
writer.write(doc);
out.close();
writer.close();
}
/**
* @param filepath 文件地址,全路径
* @param rootName xml根名 "<root></root>"则 rootName 是 root
* @param attrName 属性
*/
private Map<String, Element> readXml(String filepath, String rootName, String attrName) throws Exception {
Map<String, Element> map = new TreeMap<>();
SAXReader reader = new SAXReader();
// InputStream resourceAsStream = AttrParseTest.class.getResourceAsStream("/attrs.xml");
// Document document = reader.read(resourceAsStream);
File file = new File(filepath);
Document document = reader.read(file);
// <resources>
Element resources = document.getRootElement();
List<Element> attrElements = resources.elements();
for (Element attrElement : attrElements) {
List<Attribute> attrs = attrElement.attributes();
for (Attribute attr : attrs) {
if (attrName.equals(attr.getName())) {
map.put(attr.getValue(), attrElement);
}
}
}
return map;
}
使用 dom4j 比较两个xml文件内容,并输出结果
最新推荐文章于 2022-03-11 11:25:48 发布