如何将xml的一部分复制到另一个文档

时间:2017-04-16 07:25:13

标签: java xml parsing

我需要将xml读入另一个文件,并将元素复制指定次数到新文件中。我怎么在java中做到这一点?例如,如果这是我的xml:

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

我需要将此xml复制到另一个文档,其中我需要将员工节点及其所有子节点复制指定的“n”次。假设n = 3,我的新xml文档将是:

<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>

有人可以建议合适的java代码吗?在此先感谢:)

2 个答案:

答案 0 :(得分:0)

您可以将文件的实体表示为以下对象:

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

然后您可以根据需要填写所有数据。要以XML格式编写数据,您可以使用一些XML序列化程序。

答案 1 :(得分:0)

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