I appear to have run into a limitation of Jackson XML but wanted to ask the community first to see if I am missing something. Given the following xml:
<Element1>
<Element2 attribute="Some String">Some element value</Element2>
<Element1>
Is it possible to create a POJO to deserialize the attribute value of Element2? My current POJO looks like:
@JacksonXmlRootElement(localName = "Element1")
public class Element1 implements Serializable {
@JacksonXmlProperty(isAttribute = true)
private String attribute;
}
This returns the value of the Element2 tag which in this case is "Some element value". However if I move the attribute to the Element1 tag, this same code is able to retrieve the attribute value. Is there some limitation of jackson xml to get nested attributes? I have also tried specifying the localname of the attribute but that doesnt work either. I feel I am missing something or this is a limitation of the library. TIA.
It is possible to read a nested xml tag with an incremental reading: basically you have to create an XMLStreamReader
streamreader and set it manually so that points to the Element2
nested tag. Your xmlmapper will read the nested tag using the pointing xmlstreamreader like below:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Element2 {
@JacksonXmlProperty(isAttribute = true)
private String attribute;
}
File xml = new File("msg.xml");
XMLInputFactory f = XMLInputFactory.newFactory();
XMLStreamReader sr = f.createXMLStreamReader(new FileInputStream(xml));
XmlMapper mapper = new XmlMapper();
sr.nextTag(); //<--point to Element1
sr.nextTag(); //<--point to Element2
//now you can deserialize the nested xml tag
Element2 element2 = mapper.readValue(sr, Element2.class);
sr.close(); //<-- closing the stream