我对如何将 xml 数据附加到已经存在的数据感到非常困惑给我你的建议我的代码是这样的
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();//db.newDocument();//create document
Element root = doc.createElement("Employees");//cretae Elements
doc.appendChild(root);
Comment cmt = doc.createComment("Employee Details");//Add comment to xml
root.appendChild(cmt);
Element employee = doc.createElement("employee");//create Element
//employee.appendChild(doc.)
root.appendChild(employee);
Attr genderAttr = doc.createAttribute("Gender");
System.out.print("Enter your gender :");
String gend = br.readLine();
genderAttr.setValue(gend);
employee.setAttributeNode(genderAttr);
System.out.print("Enter first name:");
String child = br.readLine();
Element FName = doc.createElement("firstName");
FName.appendChild(doc.createTextNode(child));//set xml text
employee.appendChild(FName);
System.out.print("Enter last name:");
String child1 = br.readLine();
Element LName = doc.createElement("lastName");
LName.appendChild(doc.createTextNode(child1));
employee.appendChild(LName);
//root.appendChild(employee);
//doc.appendChild(root);
//to write on file/screen
TransformerFactory tf = TransformerFactory.newInstance();
Transformer tr = tf.newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);//source
//File shopOrder = new File("src"+File.separator+"xmlparsing"+File.separator+"xmlParse1.xml");//get the file
StreamResult res = new StreamResult(new File("src"+File.separator+"xmlparsing"+File.separator+"xmlParse1.xml"));//Destination
tr.transform(source, res);//to write on file
我也可以轻松解析和更新,但我不明白如何附加以前的数据请帮助我