4

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?

1 Answer 1

4

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"));
        }

    }

}
2
  • 1
    Thanks Blaise, I'll admit I was hoping for something like @XmlElementAntiWrapper. Just after I posted this I realized I could subclass VeryComplexObject and get the effect I want. That won't always work but it's good enough for this project. Thanks. Commented Dec 15, 2011 at 21:05
  • 1
    Is there a nicer way to do this in the meantime?
    – ppasler
    Commented Oct 7, 2017 at 18:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.