我对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
我也可以轻松解析和更新但我无法理解我如何追加以前的数据请帮帮我
答案 0 :(得分:4)
这很简单。比如说,您想要将新的Employees
附加到XML。您只需使用getElementsByName()
(例如
// find root
NodeList rootList = doc.getElementsByName("Employees");
Node root = rootList.item(0);
Element employee = doc.createElement("employee"); //create new Element
root.appendChild(employee); // append as before
如果为元素分配了标识符,也可以使用Document.getElementById()
方法。要在树的深处插入内容,请先使用XPath
查找节点,然后照常查找append()
。
编辑:(已添加示例代码)
您不能拥有两个根节点,即两个<Employees>
标记作为root。这是无效的XML。您需要的是一个根<Employee>
标记内的多个<Employees>
标记。此外,坚持骆驼或资本案件。我使用大写字母来保持一致性。
// find root
NodeList rootList = doc.getElementsByName("Employees");
Node root = rootList.item(0);
// append using a helper method
root.appendChild(createEmployee(doc, "male", "John", "Doe"));
public Element createEmployee(Document doc,
String gender, String fname, String lname) {
// create new Employee
Element employee = doc.createElement("Employee");
employee.setAttribute("gender", gender);
// create child nodes
Element firstName = doc.createElement("FirstName");
firstName.appendChild(doc.createTextNode(fname));
Element lastName = doc.createElement("LastName");
lastName.appendChild(doc.createTextNode(lname));
// append and return
employee.appendChild(firstName);
employee.appendChild(lastName);
return employee;
}