Wally Liu
Wally Liu

Reputation: 85

How to add namespace in rest XML response?

We are creating a Spring boot REST service that can support both XML and JSON formats. We are using the same approach described here: Accepting / returning XML/JSON request and response - Spring MVC

It worked mostly except that we need to have a namespace in the XML response, currently the response xml doesn't have any namespaces. We tried to add the following in the DTO class and also tried to create a "package-info.java". Neither worked. Anyone has suggestions?

@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.aa.com/bb", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED, xmlns = { @javax.xml.bind.annotation.XmlNs(prefix="ns1", namespaceURI="http://www.aa.com/bb") })

Upvotes: 0

Views: 2035

Answers (2)

Wally Liu
Wally Liu

Reputation: 85

The solution is to use "JacksonXmlRootElement" (instead of "XmlRootElement") and "JacksonXmlProperty" (instead of "XmlElement") annotations. Such as:

@JacksonXmlRootElement(namespace="http://www.aa.com/bb", localName="courseName")
public class Course implements Serializable {
    private static final long serialVersionUID = 1L;
    private String courseName;

    @JacksonXmlProperty(namespace="http://www.aa.com/bb")
    public String getCourseName() { return courseName; }

Upvotes: 1

genchev
genchev

Reputation: 102

Have you tried providing the namespace to the XMLElement or XMLRootElement like this:

@XmlRootElement(name = "student", namespace="ns1")
public class Student implements Serializable {
    private static final long serialVersionUID = 1L;

I haven't tried this in a project, but seems meaningful. Here is a similar question/answer: https://stackoverflow.com/a/46501216/402341

Upvotes: 0

Related Questions