10

If i declare the namespace on the root element, like this:

@JacksonXmlRootElement(namespace = "urn:stackify:jacksonxml", localName = "PersonData")
public class Person {
    private String id;
    private String name;
    private String note;
}

It produces:

<PersonData xmlns="urn:stackify:jacksonxml">
    <id xmlns="">12345</id>
    <name xmlns="">Graham</name>
    <note xmlns="">Hello</note>
</PersonData>

But I want the namespace only on the root element. The xmlns attribute should not appear on child elements.

How can i archive this?

Thiago Sayão
  • 2,197
  • 3
  • 27
  • 41

3 Answers3

11

There is a workaround which I found more elegant for me.

You may define constant for your namespace like this:

@JacksonXmlRootElement(localName = "PersonData")
public class Person {

    @JacksonXmlProperty(isAttribute = true)
    private final String xmlns = "urn:stackify:jacksonxml";

    private String id;
    private String name;
    private String note;
}
Andrey Sarul
  • 1,382
  • 2
  • 16
  • 20
  • 1
    +1. That's a clever hack. It creates an attribute called `xmlns` and sets it to a value. Parsers are happy with the output. However this does not define a namespace in a way that would be understood by other frameworks working with xml and your classes, JAXB for example. – Mike Dec 11 '20 at 16:25
  • xmlns is not an attribute but namespace definition – TOUDIdel Jul 12 '23 at 09:29
8

You need to specify the same namespace as the root element in each attribute:

@JacksonXmlRootElement(namespace = "urn:stackify:jacksonxml", localName = "PersonData")
public class Person {
    @JacksonXmlProperty(namespace = "urn:stackify:jacksonxml")
    private String id;
    @JacksonXmlProperty(namespace = "urn:stackify:jacksonxml")
    private String name;
    @JacksonXmlProperty(namespace = "urn:stackify:jacksonxml")
    private String note;
}

Its a bit tiresome, but its the only way I found to avoid the unnecessary namespaces.

Stempler
  • 1,309
  • 13
  • 25
  • 3
    "You need"? Why? XML is happy using the namespace declared in the root element for all elements. Isn't this a bug in Jackson? – Raphael Oct 29 '20 at 11:26
1

Also works well with immutables library and json annotations (if you need to serialize/deserialize both in JSON and in XML)

@Value.Immutable
@JsonRootName(value = "PersonData", namespace = "urn:stackify:jacksonxml")
public interface Person extends Serializable {

}
Arnaud
  • 11
  • 1