Answer the question
In order to leave comments, you need to log in
How to convert hashmap to XML attributes (JAXB)?
Good time and day!
I have an XmlResponse class:
@XmlRootElement (name = "response")
public class XMLResponse {
@XmlAttribute
Map<String, String> attributes = new HashMap<>();
public XMLResponse() {}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
}
<response result="0" version="0.4"></response>
Answer the question
In order to leave comments, you need to log in
@XmlRootElement(name = "response")
public class XMLResponse {
private Map<QName, String> attributes;
@XmlAnyAttribute
public Map<QName, String> getAttributes() {
if (attributes == null) {
attributes = new HashMap<>();
}
return attributes;
}
public void setAttributes(final Map<QName, String> attributes) {
this.attributes = attributes;
}
}
public class DynamicAttributes {
public static void main(final String[] args) {
try {
JAXBContext jc;
jc = JAXBContext.newInstance(XMLResponse.class);
final XMLResponse xmlResponse = new XMLResponse();
xmlResponse.getAttributes().put(new QName("version"), "1.1");
xmlResponse.getAttributes().put(new QName("version_old"), "1.0");
final Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(xmlResponse, System.out);
} catch (final JAXBException e) {
e.printStackTrace();
}
}
}
You create a MapAdapter class that contains the logic for marshalling your map.
Read more here: stackoverflow.com/questions/3941479/jaxb-how-to-ma...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question