jaxb抑制嵌套对象的外部标记 [英] jaxb suppress outer tag for nested objects
本文介绍了jaxb抑制嵌套对象的外部标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个复杂的对象,我从通常的我无法控制的API返回值。
I have a complex object I'm getting back as a return value from the usual "API I have no control over".
对于某些API调用,返回XML看起来像:
For some API calls the returned XML looks like:
<APICall1>
<VeryComplexObject>
<VeryComplexObjectElements... >
</VeryComplexObject>
</APICall1>
没问题,我只是用
@XmlElement
private VeryComplexObject VeryComplexObject;
并且照常营业。
但是有几个电话想要回复:
But a few calls want to return:
<APICall2>
<VeryComplexObjectElements... >
</APICall2>
是否有注释我可以用来抑制< VeryComplexObject>
unmarshal的标签,但获取内部元素标签?
Is there an annotation I can use to suppress the <VeryComplexObject>
tags for unmarshal but get the inner element tags?
推荐答案
您可以使用JAXB和StAX来完成此操作通过利用 StreamFilter
忽略XML元素:
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"));
}
}
}
这篇关于jaxb抑制嵌套对象的外部标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文