JAXB:如何在解组 XML 文档期间忽略命名空间? [英] JAXB: How to ignore namespace during unmarshalling XML document?

查看:79
本文介绍了JAXB:如何在解组 XML 文档期间忽略命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的架构指定了一个命名空间,但文档没有.在 JAXB 解组(XML -> 对象)期间忽略命名空间的最简单方法是什么?

My schema specifies a namespace, but the documents don't. What's the simplest way to ignore namespace during JAXB unmarshalling (XML -> object)?

换句话说,我有

<foo><bar></bar></foo>

代替,

<foo xmlns="http://tempuri.org/"><bar></bar></foo>

推荐答案

我相信你必须 将命名空间添加到您的 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
    }
}

这篇关于JAXB:如何在解组 XML 文档期间忽略命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆