Юрій
Юрій

Reputation: 31

How to get nested elements with JacksonXmlRootElement?

I am using Java/Spring

I have XML like this:

 <Transfer> 
 <Data>
     ... 
 </Data>
 <Transfer>

and I just need to access to XML element "Data" for my model, like: @JacksonXmlRootElement (localName = "Data")

Is it possible without additional wrapper class?

Upvotes: 0

Views: 1074

Answers (2)

Юрій
Юрій

Reputation: 31

Friendly reminder to everyone: please don't mix-up JAXB with JacksonXML. All my problems were from there.

Just add an additional model, like in code below:

@Data
@JacksonXmlRootElement(localName = "Transfer")
public class WrapperClass{

   @JacksonXmlProperty(localName="Data")
   public MyClass myClas;

}

Upvotes: 1

dariosicily
dariosicily

Reputation: 4547

Is it possible without additional wrapper class?

Yes, it is possible if you read the xml tag you are interested with the XMLStreamReader class directly pointing the involved tag, be aware you have to manually place the XMLStreamReader reader to the correct tag:

//the simplest class, the classname is the same of the <Data> tag so no need for
//@JacksonXmlRootElement (localName = "Data")
public class Data {}

XMLInputFactory f = XMLInputFactory.newFactory();
XMLStreamReader sr = f.createXMLStreamReader(new FileInputStream(xml));
XmlMapper mapper = new XmlMapper();
sr.nextTag();
sr.nextTag(); //<-- pointing the <Data> tag
Data data = mapper.readValue(sr, Data.class);
sr.close();

Upvotes: 1

Related Questions