从对象创建复杂xml文件的最简单方法

时间:2015-08-12 14:02:00

标签: java xml

从对象创建复杂xml文件的最佳选择是什么?根文件有6个孩子,有很多条目。哪些标签的值为asinged可能因文件不同而不同。

<root>
<child>
    <Child>
        <child>
            <child</child>

StaX,DOMParser或使用模板。

2 个答案:

答案 0 :(得分:0)

我喜欢将这样的东西传递给对象本身。

您可以编写如下界面:

public interface XMLWriteable {

   /** Write stuff to XML file **/
   public void writeXML( PrintWriter pWriter );
}

在你的班级中:

public class Object2XML implements XMLWriteable{
  ...
  public void writeXML( PrintWriter pWriter ){
    pWriter.println("<ObjectTag>");
    //Write Some values
    pWriter.println("<stringTag>"+value+"</stringTag>");
    //Write other complex XMLWriteable Objects
    XMLWObj.writeXML(pWriter);
    //Close your tag
    pWriter.println("</ObjectTag>");
  }
 }

然后保存对象很容易。

public static void main(String[] args){
  Object2XML obj = new Object2XML();
  //Do something with the Object
  //Save Object
  obj.writeXML(new PrintWriter("your/xml/file"));
}

这是一种可能的方式。希望我帮忙。

答案 1 :(得分:0)

您可以使用Java Architecture for XML Binding(JAXB)API来执行此操作。 我编写了简单的员工类来解释如何使用JAXB来实现它。

/*Employee class as root node*/
@XmlRootElement
public class Employee {

private String name;
private int age;
private int id;
private double salary;

public Employee() {
    super();
    // TODO Auto-generated constructor stub
}

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

/*add as attribute into root node*/
@XmlAttribute
public String getName() {
    return name;
}

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

/*add as element*/
@XmlElement
public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

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

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

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

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

}

在main方法中,您可以将此员工对象数据写入xml文件。

public static void main(String[] args) throws JAXBException,
        FileNotFoundException {

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

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

    Employee emp1 = new Employee("saman", 23, 001, 2500.00);

    marshallerObj.marshal(emp1, new FileOutputStream("employee.xml"));

}

employee.xml文件如下: -

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <employee id="1" name="saman">
    <age>23</age>
    <salary>2500.0</salary>
   </employee>

因此,您可以对java对象使用注释来构建xml文件。格式。