自定义JAXB xml输出

时间:2011-06-16 09:52:30

标签: java xml jaxb

鉴于以下课程:

public class Customer {
  public String name;
  public String lastName;
}

我想使用JAXB为name为John且lastName为Doe的客户生成以下xml输出:

<cst>John Doe</cst>

如何使用JAXB执行此操作?

修改

班级Customer用于多个地方,如下所示:

public class Sale {
  private String productId;
  private Date date;
  private Customer customer;
}

public class Transaction {
  private List<Sale> sales;
}

......等等...这笔交易是,我怎么能告诉JAXB:“无论何时看到客户,请使用自定义格式”?

我的问题是有许多类包含客户,我想以编程方式控制输出(有时name + lastname,有时<name>name</name><lastname>lastname</lastname>),而不是每次都添加注释包含Customer的类。此要求将排除使用JAXBElement<Customer>

1 个答案:

答案 0 :(得分:2)

您可以安装处理翻译的XmlAdapter

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

    JAXBContext ctxt = JAXBContext.newInstance(CustomerWrapper.class);
    Marshaller m = ctxt.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    Customer customer = new Customer("John", "Doe");
    m.marshal(new JAXBElement<CustomerWrapper>(new QName("cwrapper"), CustomerWrapper.class, new CustomerWrapper(customer)), System.err);

}

static class CustomerWrapper {
    private Customer customer;

    public CustomerWrapper() {
    }

    public CustomerWrapper(Customer customer) {
        this.customer = customer;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
}

@XmlJavaTypeAdapter(CustomerAdapter.class)
static class Customer {
    private String name;
    private String lastName;
    public Customer() {
    }
    public Customer(String name, String lastName) {
        this.name = name;
        this.lastName = lastName;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

static class CustomerAdapter extends XmlAdapter<String, Customer> {

    @Override
    public Customer unmarshal(String v) throws Exception {
        String[] ss = v.split(" ");
        return new Customer(ss[0], ss[1]);
    }

    @Override
    public String marshal(Customer v) throws Exception {
        return v.getName() + " " + v.getLastName();
    }

}

输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cwrapper>
    <customer>John Doe</customer>
</cwrapper>