gpt4 book ai didi

java - 自定义 JAXB xml 输出

转载 作者:行者123 更新时间:2023-11-30 05:01:56 26 4
gpt4 key购买 nike

给定以下类(class):

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

我想使用 JAXB 为其 name 的客户生成以下 xml 输出是约翰和 lastName是美国能源部:

<cst>John Doe</cst>

如何使用 JAXB 执行此操作?

编辑

类(class)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> .

最佳答案

您可以安装一个处理翻译的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>

关于java - 自定义 JAXB xml 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6370005/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com