JAXB:如何在解组XML文档期间忽略名称空间?
我的架构指定了一个名称空间,但是文档没有。在JAXB解组(XML-> object)期间忽略名称空间的最简单方法是什么?
换句话说,我有
<foo><bar></bar></foo>代替,
<foo xmlns="http://tempuri.org/"><bar></bar></foo>回答:
我相信你必须将名称空间添加到xml文档中,例如,使用SAX过滤器。
这意味着:
- 用一个新类定义一个ContentHandler接口,该接口将在JAXB获得它们之前拦截SAX事件。
- 定义一个XMLReader,它将设置内容处理程序然后将两者链接在一起: 
public static Object unmarshallWithFilter(Unmarshaller unmarshaller,java.io.File source) throws FileNotFoundException, JAXBException 
{
    FileReader fr = null;
    try {
        fr = new FileReader(source);
        XMLReader reader = new NamespaceFilterXMLReader();
        InputSource is = new InputSource(fr);
        SAXSource ss = new SAXSource(reader, is);
        return unmarshaller.unmarshal(ss);
    } catch (SAXException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } catch (ParserConfigurationException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } finally {
        FileUtil.close(fr); //replace with this some safe close method you have
    }
}
以上是 JAXB:如何在解组XML文档期间忽略名称空间? 的全部内容, 来源链接: utcz.com/qa/411666.html




