1

Say I want to model this:

<?xml version="1.0" encoding="UTF-8"?>
<something>
    <list>
        <entry value="bob" />
        <entry value="foo" />
    </list>
</something>

With this kind of modeling (getters and what-not are generated with Lombok, but I left these details out for the purpose of conciseness):

@XmlRootElement(name = "something")
public class Something {

  @ArraySchema(
    arraySchema = @Schema(name = "list"),
    schema = @Schema(implementation = Entry.class, name = "entry")) // this obviously doesn't work
  List<Entry> entries = new ArrayList<>();
}


public class Entry {

  @XmlAttribute
  String value;
}

My usage of @ArraySchema is clearly wrong because this is what Swagger generates for me when I press Try it out:

<?xml version="1.0" encoding="UTF-8"?>
<something>
    <entry value="string">
    </entry>
</something>

The documentation mentions xml/wrapped, and so does this SO answer, but nowhere can I find the information about how to inject that kind of information using the annotations.

payne
  • 4,691
  • 8
  • 37
  • 85

1 Answers1

0

I recently came across the same requirement and I found a working solution for my Spring Boot application (although I think that this is just a workaround).

Versions used:

org.springframework.boot:spring-boot-starter-web:2.5.5
org.springdoc:springdoc-openapi-ui:1.5.11

If you annotate your classes/fields like below, you should get the desired result.

@XmlRootElement(name = "something")
public class Something {

  @XmlElementWrapper(name = "list")
  List<Entry> entries = new ArrayList<>();
}

@XmlRootElement(name = "entry")
public class Entry {

  @XmlAttribute
  String value;
}

The important part here is @XmlElementWrapper(name = "list") which contributes the wrapper element. @XmlRootElement(name = "entry") is also necessary, otherwise the "item element" will not have the right name.


Edit: I just saw the mention of "Try it out". If your API response is not properly converted (I assume the use of com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.12.5) rather than the Schema in the Swagger UI, you might need to add the Jackson annotations as well:

@XmlRootElement(name = "something")
public class Something {

  @JacksonXmlElementWrapper(localName = "list")
  @JacksonXmlProperty(localName = "entry")
  @XmlElementWrapper(name = "list")
  List<Entry> entries = new ArrayList<>();
}
Miche
  • 66
  • 7