且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何追加使用DOM而不覆盖现有数据的现有XML文件?在java中

更新时间:2023-09-20 14:42:58

这是pretty容易。再说了,你想新的员工追加到XML。而不是创建一个新的根你会使用简单的找到它 getElementsByName()

It's pretty easy. Say, you want to append new Employees to your XML. Instead of creating a new root you'd simply find it using getElementsByName() like

// 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 找到节点首先那么追加()如常。

There's a Document.getElementById() method as well that you could use if an element has been assigned an identifier. To insert something deep down the tree use XPath to find the node first then append() as usual.

修改(样本code加)

你不能有两个根节点,即两个<员工与GT; 标记根。这是无效的XML。你需要的是多个<员工> 一个单一的根里面标记<员工与GT; 标记。此外,坚持要么骆驼或死刑案件。我使用的是首都的一致性。

EDIT : (Sample code added)
You can't have two root nodes i.e. two <Employees> tags as root. That's invalid XML. What you need is multiple <Employee> tags inside one single root <Employees> tag. Also, stick to either camel or capital case. I'm using capitals for consistency.

// 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;
}