簡體   English   中英

使用JAXB從Java對象創建xml

[英]create xml from java object using JAXB

大家好,我有java對象,我必須將其轉換為xml。 例如這樣的課程

package com.test.xml;

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

@XmlRootElement
public class Customer {

String name;
int age;

public String getName() {
    return name;
}

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

public int getAge() {
    return age;
}

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

}

並轉換為xml

package com.test.xml;

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

public class JAXBExample {
 public static void main(String[] args) {

  Customer customer = new Customer();
  customer.setName("testName");
  customer.setAge(25);

  try {

    File file = new File("C:\\testXml.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.marshal(customer, file);
    jaxbMarshaller.marshal(customer, System.out);

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

}

}

這將創建這樣的xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
  <age>25</age>
  <name>testName</name>
</customer>

和我的問題。 如何從這樣的客戶對象創建xml?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
  <customerInfo>
    <age>25</age>
    <name>testName</name>
  </customerInfo>
</customer>

1.創建一個客戶類

2.創建一個CustomerInfo類

3.客戶有CustomerInfo

4.現在使用Jaxb創建您的xml文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM