Reputation: 2239
I have a complex object I'm getting back as a return value from the usual "API I have no control over".
For some API calls the returned XML looks like:
<APICall1>
<VeryComplexObject>
<VeryComplexObjectElements... >
</VeryComplexObject>
</APICall1>
No problem, I just use
@XmlElement
private VeryComplexObject VeryComplexObject;
and it's business as usual.
But a few calls want to return:
<APICall2>
<VeryComplexObjectElements... >
</APICall2>
Is there an annotation I can use to suppress the <VeryComplexObject>
tags for unmarshal but get the inner element tags?
Upvotes: 4
Views: 1205
Reputation: 149047
You could use JAXB with StAX to accomplish this by leveraging a StreamFilter
to ignore an XML element:
package forum8526002;
import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
import javax.xml.stream.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Foo.class);
XMLInputFactory xif = XMLInputFactory.newFactory();
StringReader xml = new StringReader("<APICall2><VeryComplexObjectElements><Bar>Hello World</Bar></VeryComplexObjectElements></APICall2>");
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
xsr = xif.createFilteredReader(xsr, new Filter());
Unmarshaller unmarshaller = jc.createUnmarshaller();
Foo foo = (Foo) unmarshaller.unmarshal(xsr);
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(foo, System.out);
}
@XmlRootElement(name="APICall2")
static class Foo {
@XmlElement(name="Bar")
private String bar;
}
static class Filter implements StreamFilter {
@Override
public boolean accept(XMLStreamReader reader) {
return !(reader.isStartElement() && reader.getLocalName().equals("VeryComplexObjectElements"));
}
}
}
Upvotes: 4