I
I
ingush2016-12-27 15:33:57
Java
ingush, 2016-12-27 15:33:57

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;
    }
}

Guys, please tell me how to convert Map attributes = new HashMap<>(); into XML attributes to look something like this: Why hashmap? My attributes can be different and in different quantities
<response result="0" version="0.4"></response>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
al_gon, 2016-12-27
@ingush

@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;
  }
}

main:
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();
    }

  }
}

A
Alexander Oparin, 2016-12-27
@losse_narmo

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 question

Ask a Question

731 491 924 answers to any question