嗨,我需要使用Jackson-dataformat XMLMapper从JAVA创建XML.
XML应该是这样的
XML应该是这样的
<Customer> <id>1</id> <name>Mighty Pulpo</name> <addresses> <city>austin</city> <state>TX</state> </addresses> <addresses> <city>Hong Kong</city> <state>Hong Kong</state> </addresses> </Customer>
但我总是喜欢额外的“< addresses>< / addresses>”标签.
<Customer> <id>1</id> <name>Mighty Pulpo</name> <addresses> <addresses> <city>austin</city> <state>TX</state> </addresses> <addresses> <city>Hong Kong</city> <state>Hong Kong</state> </addresses> <addresses> </Customer>
我使用下面的代码来创建XML
JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule(); XmlMapper mapper = new XmlMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.registerModule(jaxbAnnotationModule); mapper.registerModule(new GuavaModule()); String xml = mapper.writeValueAsString(customer); System.out.println(xml);
请尝试以下代码
@JacksonXmlRootElement(localName = "customer") class Customer { @JacksonXmlProperty(localName = "id") private int id; @JacksonXmlProperty(localName = "name") private String name; @JacksonXmlProperty(localName = "addresses") @JacksonXmlElementWrapper(useWrapping = false) private Address[] address; //getters,setters,toString } class Address { @JacksonXmlProperty(localName = "city") private String city; @JacksonXmlProperty(localName = "state") private String state; // getter/setter }