【问题标题】:JAXB: Validating XML Enum as String while preserving type in XSDJAXB:将 XML 枚举验证为字符串,同时在 XSD 中保留类型
【发布时间】:2015-04-09 08:37:36
【问题描述】:

我的运输类带有注释:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType
public class PersonalData {

  @XmlElement
  private ETSalutation salutation;

}

生成的 XSD 很好:

<xs:element name="salutation" type="tns:ETSalutation"/>

已知的事实是,当在传入的 XML 中找到未知值时,JAXB 将设置为 null。我需要检查它,所以我想使用 XmlAdapter 进行内部验证。但是当我实现一个适配器时:

 class ETSalutationEnumAdapter implements XmlAdapter<String, ETSalutation>

并附上:

  @XmlElement
  @XmlJavaTypeAdapter(ETSalutationEnumAdapter.class)
  private ETSalutation salutation;

...我在 XSD 中得到一个字符串类型:

<xs:element name="salutation" type="xs:string"/>

当我使用 @XmlElement(type = ETSalutation.class) 强制类型时,在适配器中我将得到 ClassCastException。

所以,长话短说:我怎样才能在 XSD 中保留我的 Enum 类型并且仍然能够访问它的传入原始字符串值?

布莱斯? :)

【问题讨论】:

    标签: java enums jaxb


    【解决方案1】:

    由于没有发布任何答案,这里我做了什么(肮脏的黑客,但工作......): 放弃适配器,显然他们无法处理。

    我已经介绍了我自己的班级 com.sun.xml.bind.v2.model.impl.RuntimeEnumLeafInfoImpl

    阴影原来的那个。类体是一样的,只是 parse(CharSequence lexical) 方法有一个变化,现在看起来像这样:

    @Override
    public T parse(CharSequence lexical) throws AccessorException, SAXException {
    
        B b = this.baseXducer.parse(lexical);
    
        if (this.tokenStringType) {
            b = (B) ((String) b).trim();
        }
    
        T value = this.parseMap.get(b);
    
        // no value found, means incorrect value in incoming XML
        if (value == null) {
            // find out XML field name
            String fieldName = StringUtils.substringAfterLast(getUpstream().getLocation().toString(), ".");
            // add error data to context
            Triple error = Triple.of(getClazz(), fieldName, lexical.toString());
            // Context is my own class, which contains ThreadLocal field to gather all errors
            Context.getJaxbEnumErrors().add(error);
            LOG.debug("Enum parsing error: " + error);
        }
    
        return value;
    }
    

    根据我的 Triple 中的数据,我现在可以匹配我需要报告错误的 XML 中的位置,并且我的值无效 :) 但是解决方案非常脏

    【讨论】:

      猜你喜欢
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-03
      • 2016-05-02
      • 1970-01-01
      • 2018-02-14
      • 2019-01-22
      • 2020-01-20
      相关资源
      最近更新 更多