如何使用SAX初始化JAXB [英] How to initilize JAXB with SAX
问题描述
我正在尝试使用带有SAX的JAXB将xml编组为java对象.我在构造函数中编写了这段代码.
I am trying to unmarshall an xml to java object using JAXB with SAX. I wrote this code in the constructor.
logger.debug("Initializing jaxb...");
try {
jaxbContext = JAXBContext.newInstance(ProductInventory.class);
jaxbUnmarshaller = jaxbContext.createUnmarshaller();
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
reader = saxParserFactory.newSAXParser().getXMLReader();
EntityResolver entityResolver = new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId,
String systemId) {
return new InputSource(new StringReader(""));
}
};
reader.setEntityResolver(entityResolver);
logger.debug("Successfully initialized jaxb.");
} catch (JAXBException | SAXException | ParserConfigurationException e) {
logger.error("Exception while initializing JAXB", e);
}
当多个请求到来时,reader
对象是否存在任何问题?我是否必须始终获得reader
的引用?我的意思是,每次取消编组操作都必须获得一个新的xml读取器吗?
Is there any problem with the reader
object when multiple requests come? Do I have to get a reference of reader
always? I mean for every unmarshall action do I have to get a new xml reader?
推荐答案
将SAX与JAXB一起使用时,您使用的是UnmarshallerHandler
而不是Unmarshaller
.
When using SAX with JAXB you leverage UnmarshallerHandler
and not Unmarshaller
.
UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();
reader.setContentHandler(unmarshallerHandler);
reader.parse(xml);
Foo foo = (Foo) unmarshallerHandler.getResult();
UnmarshallerHandler
不是线程安全的,因此请确保没有共享线程.您可以使用相同的XMLReader
UnmarshallerHandler
is not thread safe so make sure you don't have threads sharing it. You can parse multiple XML documents with the same XMLReader
这篇关于如何使用SAX初始化JAXB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!