2015-07-14 1 views
0

Это моя программа. Правильный ли способ слияния двух объектов?Как мы можем объединить два java-объекта в один файл xml?

public class ObjectToXml { 
public static void main(String[] args) throws Exception{ 
JAXBContext contextObj = JAXBContext.newInstance(Employee.class); 

Marshaller marshallerObj = contextObj.createMarshaller(); 
marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
try{ 
    Employee employees = new Employee(); 
    employees.setEmployee(new ArrayList<Employee>()); 

    Employee emp1=new Employee(1,"Vimal Jaiswal",50000); 
    Employee emp2=new Employee(2,"Kamal",40000); 

    employees.getEmployee().add(emp1); 
    employees.getEmployee().add(emp2); 
    marshallerObj.marshal(employees, new FileOutputStream("E:\\employee.xml")); 

    } 
    catch(JAXBException e){ 
    System.out.println(e); 
}}} 

Его давая выход Как раз Doulbe:

1,"Vimal Jaiswal",50000 
2,"Kamal",40000 
1,"Vimal Jaiswal",50000 
2,"Kamal",40000 
+0

вы можете загрузить вывод XML , вы указываете данные типа файла CSV. –

ответ

0

Пожалуйста, найдите код, приведенный ниже, чтобы решить вашу проблему,

package com.mss.sample; 

import javax.xml.bind.annotation.XmlElement; 

/** 
* Employee Model class 
* 
* @author Anilkumar Bathula 
*/ 


public class Employee { 

    // Fields 
    int empId; 
    String empName; 
    int empSal; 

    public Employee(int empId, String empName, int empSal) { 
     super(); 
     this.empId = empId; 
     this.empName = empName; 
     this.empSal = empSal; 
    } 

    @XmlElement 
    public int getEmpId() { 
     return empId; 
    } 

    public void setEmpId(int empId) { 
     this.empId = empId; 
    } 

    @XmlElement 
    public String getEmpName() { 
     return empName; 
    } 

    public void setEmpName(String empName) { 
     this.empName = empName; 
    } 

    @XmlElement 
    public int getEmpSal() { 
     return empSal; 
    } 

    public void setEmpSal(int empSal) { 
     this.empSal = empSal; 
    } 

} 

Serialize класс:

package com.mss.sample; 

import java.util.ArrayList; 
import java.util.List; 

import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 

/** 
* Employees class 
* 
* @author Anilkumar Bathula 
*/ 

@XmlRootElement 
public class Employees { 
    private List<Employee> employees; 

    public Employees() { 
     employees = new ArrayList<Employee>(); 
    } 

    @XmlElement 
    public List<Employee> getEmployees() { 
     return employees; 
    } 

    public void setEmployees(List<Employee> employees) { 
     this.employees = employees; 
    } 
} 

MainClass генерирующего XML:

package com.mss.sample; 

import java.io.FileOutputStream; 

import javax.xml.bind.JAXBContext; 
import javax.xml.bind.JAXBException; 
import javax.xml.bind.Marshaller; 
import com.mss.sample.Employees; 

/** 
* Marshal class 
* 
* @author Anilkumar Bathula 
*/ 

public class Marshal { 

    public static void main(String[] args) throws Exception { 

     JAXBContext contextObj = JAXBContext.newInstance(Employees.class); 

     Marshaller marshallerObj = contextObj.createMarshaller(); 
     marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     try { 

      Employees employees = new Employees(); 
      Employee emp1 = new Employee(1, "Vimal Jaiswal", 50000); 
      Employee emp2 = new Employee(2, "Kamal", 40000); 

      employees.getEmployees().add(emp1); 
      employees.getEmployees().add(emp2); 
      marshallerObj.marshal(employees, new FileOutputStream(
        "D:\\employee.xml")); 

     } catch (JAXBException e) { 
      System.out.println(e); 
     } 
    } 
} 
+0

спасибо. Работает. –

+0

Добро пожаловать @MadhaviTalla –

0

Вы должны использовать примерочных с-ресурсами, чтобы закрыть FileStream объект:

try(FileOutputStream os = new FileOutputStream("c:\\temp\\employee.xml")){ 
... 

marshallerObj.marshal(employees, os); 

} 
0

Создать класс со списком объектов Employee

public class EmployeeList { 

private List<Employee> list; 

public EmployeeList(){ 
    list = new ArrayList<Employee>(); 
} 

public void add(Employee e){ 
    list.add(e); 
} 

}

Тогда сериализуете

XStream xstream = new XStream(); 
xstream.alias("employee", Employee.class); 
xstream.alias("employees", EmployeeList.class); 
xstream.addImplicitCollection(EmployeeList.class, "list"); 

EmployeeList list = new EmployeeList(); 
list.add(new Employee(1,"Vimal Jaiswal",50000)); 
list.add(new Employee(2,"Kamal",40000)); 

String xml = xstream.toXML(list); 

Я надеюсь, что это поможет.

+0

XStream получает ошибку , я не получил xstream-1.4.7. баночка. –

+0

вы можете скачать его здесь. http://x-stream.github.io/download.html – VIVEK

2

Предоставление точного ответа без применения и аннотации вашего класса Employee сложно.

Поэтому я написал небольшой пример, который очень связан с вашим. Надеюсь, это полезно :)

Подсказка: важная часть написания XML-аннотаций.

Main.class

import java.io.FileOutputStream; 
import javax.xml.bind.JAXBContext; 
import javax.xml.bind.JAXBException; 
import javax.xml.bind.Marshaller; 

public class Main { 
    public static void main(String[] args) throws Exception { 
     JAXBContext contextObj = JAXBContext.newInstance(Employees.class); 

     Marshaller marshallerObj = contextObj.createMarshaller(); 
     marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     try { 
      Employees employees = new Employees(); 
      Employee emp1 = new Employee(1, "Vimal Jaiswal", 50000); 
      Employee emp2 = new Employee(2, "Kamal", 40000); 

      employees.getEmployees().add(emp1); 
      employees.getEmployees().add(emp2); 
      marshallerObj.marshal(employees, new FileOutputStream(
        "W:\\employee.xml")); 

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

Employees.class

import java.util.ArrayList; 
import java.util.List; 

import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 

@XmlRootElement 
public class Employees { 
    private List<Employee> employees; 

    public Employees() { 
     employees = new ArrayList<Employee>(); 
    } 

    @XmlElement 
    public List<Employee> getEmployees() { 
     return employees; 
    } 

    public void setEmployees(List<Employee> employees) { 
     this.employees = employees; 
    } 
} 

Employee.class

import javax.xml.bind.annotation.XmlElement; 

public class Employee { 
    private int id; 
    private String name; 
    private int salary; 

    public Employee(int id, String name, int salary) { 
     this.id = id; 
     this.name = name; 
     this.salary = salary; 
    } 

    @XmlElement 
    public int getId() { 
     return id; 
    } 

    public void setId(int id) { 
     this.id = id; 
    } 

    @XmlElement 
    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    @XmlElement 
    public int getSalary() { 
     return salary; 
    } 

    public void setSalary(int salary) { 
     this.salary = salary; 
    } 
} 

Полученный XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<employees> 
    <employees> 
     <id>1</id> 
     <name>Vimal Jaiswal</name> 
     <salary>50000</salary> 
    </employees> 
    <employees> 
     <id>2</id> 
     <name>Kamal</name> 
     <salary>40000</salary> 
    </employees> 
</employees> 
+0

Ого уже вы это сделали, отлично @pytheos –

Смежные вопросы