且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JAXB:如何在解组 XML 文档期间忽略命名空间?

更新时间:2022-11-03 09:34:02

我相信你必须 将命名空间添加到您的 xml 文档中,例如,使用 SAX 过滤器.

I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.

这意味着:

  • 使用新类定义 ContentHandler 接口,该类将在 JAXB 获取 SAX 事件之前拦截它们.
  • 定义一个 XMLReader 来设置内容处理程序

然后将两者链接在一起:

then link the two together:

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
    }
}