我有一个复杂的对象,我正在从通常的“我无法控制的API”返回值。
对于某些API调用,返回的XML如下所示:
<APICall1>
<VeryComplexObject>
<VeryComplexObjectElements... >
</VeryComplexObject>
</APICall1>
没问题,我只是用
@XmlElement
private VeryComplexObject VeryComplexObject;
和往常一样。
但有几个电话想要回来:
<APICall2>
<VeryComplexObjectElements... >
</APICall2>
我是否可以使用注释来取消unmarshal的<VeryComplexObject>
标记但获取内部元素标记?
答案 0 :(得分:4)
您可以使用JAXB和StAX通过利用StreamFilter
忽略XML元素来实现此目的:
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"));
}
}
}