本文介绍了当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);


推荐答案

你需要打电话给使无效的XML内容失败。

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

这篇关于当Jaxb解组时,希望未知属性出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 19:48