如何在不覆盖现有数据的情况下使用DOM附加现有的XML文件?在java中

时间:2021-09-07 20:27:04

i have a very confused about the how the xml data can be append to already existed data give me your suggestions my code is like this

我对如何将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

and i can do easily parse and update also but i can't understand how i can append previous data please help me

我可以很容易地解析和更新,但是我不明白如何添加以前的数据请帮助我

1 个解决方案

#1


4  

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

它很简单。比方说,您希望将新员工添加到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

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.

还有一个Document.getElementById()方法,如果给一个元素分配了一个标识符,您可以使用它。要在树的深处插入一些东西,请使用XPath首先找到节点,然后像往常一样追加()。

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.

编辑:(添加示例代码)您不能有两个根节点,即两个 标记作为根。这是无效的XML。您需要的是在单个根 标记中包含多个 标记。同时,坚持骆驼牌或大写的情况。我用大写来表示一致性。

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

#1


4  

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

它很简单。比方说,您希望将新员工添加到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

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.

还有一个Document.getElementById()方法,如果给一个元素分配了一个标识符,您可以使用它。要在树的深处插入一些东西,请使用XPath首先找到节点,然后像往常一样追加()。

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.

编辑:(添加示例代码)您不能有两个根节点,即两个 标记作为根。这是无效的XML。您需要的是在单个根 标记中包含多个 标记。同时,坚持骆驼牌或大写的情况。我用大写来表示一致性。

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