Jackson XML deserialization of namespaces attributes to object

Viewed 142
@JacksonXmlRootElement(localName = "model_trees")
public class ModelTrees {
    @JacksonXmlProperty(isAttribute = true, localName = "xmlns")
    private String some_text1;
    @JacksonXmlProperty(localName = "tree_kind")
    private String treeKind;
}

XML:
<model_trees xmlns="http://test.com/test1">
       <tree_kind>kind</tree_kind>
</model_trees>

after deserialization:

XmlMapper xmlMapper = new XmlMapper();
ModelTrees modelTrees = xmlMapper.readValue(xml, ModelTrees.class);

I get field some_text1 with null value. But if I replace "xmlns" with attribute "id" everywhere, then I get the value I need (http://test.com/test1)

How to deserialize "xmlns" namespace attribute with XmlMapper?

1 Answers

How to deserialize "xmlns" namespace attribute with XmlMapper?

This is not normally possible because namespace declarations are not attributes but metadata, so the standard XmlMapper mapper ignores them as attributes. To achieve your goal you can instantiate a new mapper turning off the namespace support so the namespace will be reported as a regular attribute, so you need to construct a new mapper with the proper settings passing a XMLInputFactory factory:

//instantiate a factory without namespace support
XMLInputFactory inputF = XMLInputFactory.newFactory();
inputF.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);

//instantiate a mapper without namespace support
//then namespace will be reported as a regular attribute
XmlMapper xmlMapper = new XmlMapper(inputF);
ModelTrees modelTrees = mapper.readValue(xmlMapper, ModelTrees.class);
Related