当Jaxb解组时,希望未知属性出错

编程入门 行业动态 更新时间:2024-10-23 14:22:29
本文介绍了当Jaxb解组时,希望未知属性出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Jaxb将XML解组为java对象。我需要知道XML中的新属性/元素何时失败。但是默认情况下,unmarshaller忽略了新的元素/属性。

I'm using Jaxb to unmarshal XML into a java object. I need to know when new attributes/elements are in the XML and fail. However by default the unmarshaller is ignoring new elements/attributes.

当XML中存在未指定的新属性/元素时,是否存在可以设置为失败的配置POJO?

Is there a configuration I can set to fail when new attributes/elements exist in the XML that are not specified in the POJO?

我的POJO:

import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "ROOT") public class Model { private A a; public A getA() { return a; } @XmlElement(name = "A") public void setA(A a) { this.a = a; } static class A { String country; public String getCountry() { return country; } @XmlAttribute(name = "Country") public void setCountry(String country) { this.country = country; } } }

解组代码:

JAXBContext jaxbContext = JAXBContext.newInstance(Model.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); String sample = "<ROOT>" + "<A Country=\"0\" NewAttribute=\"0\"></A>" + "<NEWELEMENT> </NEWELEMENT>" + "</ROOT>"; InputStream stream = new ByteArrayInputStream(sample.getBytes(StandardCharsets.UTF_8)); Object unmarshal = jaxbUnmarshaller.unmarshal(stream);

推荐答案

你需要打电话给 Unmarshaller.setEventHandler() 使无效的XML内容失败。

You need to call Unmarshaller.setEventHandler() to make invalid XML content fail.

更多推荐

当Jaxb解组时,希望未知属性出错

本文发布于:2023-11-15 16:55:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1596272.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   Jaxb   解组时

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!