我有一些問題,在刪除和複製相同的XML元素。問題是我有2個XML文件,並在比較兩者後,我想刪除這些元素只在file1中,並在同一副本我想複製這些元素在一個新生成的XML。我可以刪除這些元素,但我無法將它們複製到另一個xml文件中。刪除一個XML元素和複製相同的元素在一個新的XML - 在java
下面是代碼:
for (Map.Entry<String, Element> entry : Map1.entrySet()) {
String key = entry.getKey();
if (!Map2.containsKey(key)) {
Map1.remove(key);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc= builder.newDocument();
Element rootElement =
doc.createElementNS("", "missing");
doc.appendChild(rootElement);
//here i want to copy the deleted element in new xml file.
//rootElement.appendChild(Map1.get(key));
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult newXml = new StreamResult(new File("C:/user/desktop/Output.xml"));
transformer.transform(source, newXml);
}
}
如果您可以發佈您的XML樣本,我會提交一個最有效/最有效的代碼示例,比您發佈的笨拙的dom代碼更好... –