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

查看:663
本文介绍了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天全站免登陆