【发布时间】:2018-01-27 07:11:53
【问题描述】:
我想将Object 转换为XML。我正在使用com.fasterxml.jackson.dataformat.xml.XmlMapper 将对象序列化为 xml
我使用javax.xml.bind.annotation.* 来注释类和变量。
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Transaction {
@XmlAttribute(required = true, name = "ch-full-name")
private String fullName;
@XmlAttribute(required = true, name = "ch-address")
private String address;
@XmlAttribute(required = true, name = "ch-city")
private String city;
@XmlAttribute(required = true, name = "ch-zip")
private String zipCode;
@XmlAttribute(required = true, name = "ch-country")
private String country;
@XmlAttribute(required = true, name = "ch-phone")
private String phone;
@XmlAttribute(required = true, name = "ch-email")
private String email;
...getters; & setters;
}
赋值和序列化:
Transaction tran = new Transaction();
tran.setFullName("full name");
tran.setAddress("address");
tran.setEmail("email");
tran.setCity("city");
tran.setCountry("country");
tran.setZipCode("zip");
tran.setPhone("phone");
XmlMapper mapper = new XmlMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String xml = "<?xml version='1.0' encoding='UTF-8'?>" +
mapper.writeValueAsString(tran);
所以xml 返回如下内容:
<?xml version="1.0" encoding="UTF-8"?>
<Transaction>
<fullName>full name</fullName>
<address>address</address>
<city>city</city>
<zipCode>zip</zipCode>
<country>country</country>
<phone>phone</phone>
<email>email</email>
</Transaction>
但实际上应该是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<transaction>
<ch-full-name>full name</ch-full-name>
<ch-address>address</ch-address>
<ch-city>city</ch-city>
<ch-zip>zip</ch-zip>
<ch-country>country</ch-country>
<ch-phone>phone</ch-phone>
<ch-email>email</ch-email>
</transaction>
是否有正确的方法来设置 xml 的属性名称?如何更改包括类名在内的名称(Transaction 名称应为 transaction)?
【问题讨论】:
标签: java xml spring serialization jackson