【发布时间】:2012-02-11 21:09:14
【问题描述】:
有许多通过 XSLT流式传输 XML,然后将 JAXB 转换为 Java 对象的示例。它们通常看起来像这样:
Transformer responseTransformer = TransformerFactory.newInstance().newTransformer(new StreamSource(getClass().getResourceAsStream("ResponseTransformation.xsl")));
Unmarshaller jaxbUnmarshaller = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName()).createUnmarshaller();
JAXBResult jaxbResult = new JAXBResult(jaxbUnmarshaller);
responseTransformer.transform(new StreamSource(new StringReader(responseXml)), jaxbResult);
res = jaxbResult.getResult();
还有这样的 declared type 的 JAXB Unmarshal 示例(来自 Unmarshaller javadoc):
JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File( "nosferatu.xml"));
Element fooSubtree = ...; // traverse DOM till reach xml element foo, constrained by a
// local element declaration in schema.
// FooType is the JAXB mapping of the type of local element declaration foo.
JAXBElement<FooType> foo = u.unmarshal(fooSubtree, FooType.class);
注意我们如何在u.unmarshal(fooSubtree, FooType.class) 调用中为根元素指定FooType.class。不错。
问题是: 有没有办法将上面示例中的流处理方式与下面示例中指定声明类型的方式结合起来?
我喜欢一种实现方式,但它需要访问 JAXB 实现类。当然可以通过公共 JAXB 接口来实现,对吧?
谢谢!
【问题讨论】: