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

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


换句话说,我有


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

代替,


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


动漫人物
浏览 760回答 3
3回答

拉莫斯之舞

我相信您必须将名称空间添加到xml文档中,例如,使用SAX过滤器。这意味着:用新类定义一个ContentHandler接口,该接口将在JAXB获取它们之前拦截SAX事件。定义一个XMLReader,它将设置内容处理程序然后将两者链接在一起:public static Object unmarshallWithFilter(Unmarshaller unmarshaller,java.io.File source) throws FileNotFoundException, JAXBException&nbsp;{&nbsp; &nbsp; FileReader fr = null;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; fr = new FileReader(source);&nbsp; &nbsp; &nbsp; &nbsp; XMLReader reader = new NamespaceFilterXMLReader();&nbsp; &nbsp; &nbsp; &nbsp; InputSource is = new InputSource(fr);&nbsp; &nbsp; &nbsp; &nbsp; SAXSource ss = new SAXSource(reader, is);&nbsp; &nbsp; &nbsp; &nbsp; return unmarshaller.unmarshal(ss);&nbsp; &nbsp; } catch (SAXException e) {&nbsp; &nbsp; &nbsp; &nbsp; //not technically a jaxb exception, but close enough&nbsp; &nbsp; &nbsp; &nbsp; throw new JAXBException(e);&nbsp; &nbsp; } catch (ParserConfigurationException e) {&nbsp; &nbsp; &nbsp; &nbsp; //not technically a jaxb exception, but close enough&nbsp; &nbsp; &nbsp; &nbsp; throw new JAXBException(e);&nbsp; &nbsp; } finally {&nbsp; &nbsp; &nbsp; &nbsp; FileUtil.close(fr); //replace with this some safe close method you have&nbsp; &nbsp; }}

沧海一幻觉

我在XMLFilter解决方案中遇到编码问题,因此我使XMLStreamReader忽略名称空间:class XMLReaderWithoutNamespace extends StreamReaderDelegate {&nbsp; &nbsp; public XMLReaderWithoutNamespace(XMLStreamReader reader) {&nbsp; &nbsp; &nbsp; super(reader);&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public String getAttributeNamespace(int arg0) {&nbsp; &nbsp; &nbsp; return "";&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public String getNamespaceURI() {&nbsp; &nbsp; &nbsp; return "";&nbsp; &nbsp; }}InputStream is = new FileInputStream(name);XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);XMLReaderWithoutNamespace xr = new XMLReaderWithoutNamespace(xsr);Unmarshaller um = jc.createUnmarshaller();Object res = um.unmarshal(xr);
打开App,查看更多内容
随时随地看视频慕课网APP