简体   繁体   中英

how to copy part of an xml to another document

I need to read an xml into another file and copy an element for a specified number of times into the new file. How do I do it in java? For example, if this is my xml to read:

<company>
  <name> XYZ </name>
  <address> a123 </address>
  <department>
    <name> HR </name>
    <employee>
      <name>ABC</name>
      <phone> 12345 </phone>
    </employee>
  </department>
</company>

I need to copy this xml to another document wherein I need to copy the employee node and all it's child nodes for a specified 'n' number of times. Suppose n = 3, my new xml document will be :

<company>
  <name> XYZ </name>
  <address> a123 </address>
  <department>
    <name> HR </name>
    <employee>
      <name>ABC</name>
      <phone> 12345 </phone>
    </employee>
    <employee>
      <name>LMN</name>
      <phone> 45678 </phone>
    </employee>
    <employee>
      <name>PQR</name>
      <phone> 34567 </phone>
    </employee>
  </department>
</company>

Can someone suggest suitable java code to do this ? Thanks in advance :)

You can represent the entities of your file as the following objects:

public class Employee{
     private String name;
     private String phone;
}

public class Department{
     private String name;
     private List<Employee> employees;
}

public class Company{
     private String name;
     private String address;
     private List <Department> departments;
}

and then you can fill all your data as you need. For writing the data in XML, you can use some XML serializer.

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class XMLWriterDOM {

    public static void main(String[] args) {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.newDocument();
            //add elements to Document
            Element rootElement =
                doc.createElementNS("your file path", "department");
            //append root element to document
            doc.appendChild(rootElement);

            //append first child element to root element
            rootElement.appendChild(getEmployee(doc, "LMN", "45678"));

            //append second child
            rootElement.appendChild(getEmployee(doc,"PQR", "34567"));

            //for output to file, console
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            //for pretty print
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);

            //write to console or file
            StreamResult console = new StreamResult(System.out);
            StreamResult file = new StreamResult(new File("/Users/pankaj/emps.xml"));

            //write data
            transformer.transform(source, console);
            transformer.transform(source, file);
            System.out.println("DONE");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static Node getEmployee(Document doc, String name, String phone) {
        Element employee = doc.createElement("employee");

        //create name element
        employee.appendChild(getEmployeeElements(doc, employee, "name", name));

        //create age element
        employee.appendChild(getEmployeeElements(doc, employee, "phone", phone));

        return employee;
    }


    //utility method to create text node
    private static Node getEmployeeElements(Document doc, Element element, String name, String value) {
        Element node = doc.createElement(name);
        node.appendChild(doc.createTextNode(value));
        return node;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM