Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Xml: How to add namespace only on root?

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?

like image 244
Thiago Sayão Avatar asked Aug 21 '18 11:08

Thiago Sayão


People also ask

What is @JacksonXmlRootElement?

Annotation Type JacksonXmlRootElementAnnotation that can be used to define name of root element used for the root-level object when serialized, which normally uses name of the type (class). It is similar to JAXB XmlRootElement .

Can ObjectMapper be used for XML?

We can also read XML, using the various readValue APIs that are part of provided by the ObjectMapper. For example, reading some XML from an InputStream into a Java Bean: MyBean bean = objectMapper.

What is Jackson Dataformat XML?

dataformat. xml. annotation. Package that contains additional annotations that can be used to configure XML-specific aspects of serialization and deserialization.


1 Answers

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;
}
like image 167
Andrey Sarul Avatar answered Oct 09 '22 14:10

Andrey Sarul