【问题标题】:How do I mark fields as required/optional when reading XML with MOXy?使用 MOXy 读取 XML 时,如何将字段标记为必填/可选?
【发布时间】:2011-08-25 14:58:26
【问题描述】:

有这样一个简单的代码:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class A {
  @XmlPath("B/text()")
  private String b;

  @XmlPath("C/text()")
  private Integer c;
  ...
}

只要我的 XML 中有合适的值,它就可以正常工作。我想根据需要标记字段c,因此每次我尝试阅读未设置c 或无效的文档时都会抛出MOXy。最简单的解决方案是什么?

更新:

设置默认值也可以。

【问题讨论】:

    标签: java xml xsd eclipselink moxy


    【解决方案1】:

    EclipseLink JAXB (MOXy) 或任何 JAXB 实现不会对缺失的节点执行设置操作,因此您可以执行以下操作:

    选项 #1 - 默认字段值

    import javax.xml.bind.annotation.*;
    import org.eclipse.persistence.oxm.annotations.XmlPath;
    
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    class A {
      @XmlPath("B/text()")
      private String b = "fieldDefault";
    
      @XmlPath("C/text()")
      private Integer c;
    }
    

    使用以下演示代码:

    import java.io.StringReader;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Unmarshaller;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(A.class);
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            A a = (A) unmarshaller.unmarshal(new StringReader("<a/>"));
    
            System.out.println(a.getB());
            System.out.println(a.getC());
        }
    
    }
    

    将产生以下输出:

    fieldDefault
    null
    

    选项 #2 - 在 @XmlElement 上指定 defaultValue

    您可以在 @XmlElement 注释上指定 defaultValue,但这只会在解组空元素时设置 defaultValue。

    import javax.xml.bind.annotation.*;
    import org.eclipse.persistence.oxm.annotations.XmlPath;
    
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    class A {
      @XmlPath("B/text()")
      @XmlElement(defaultValue="annotationDefault")
      private String b;
    
      @XmlPath("C/text()")
      @XmlElement(defaultValue="annotationDefault")
      private Integer c;
    
    }
    

    使用以下演示代码:

    import java.io.StringReader;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Unmarshaller;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(A.class);
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            A a = (A) unmarshaller.unmarshal(new StringReader("<a><B/></a>"));
    
            System.out.println(a.getB());
            System.out.println(a.getC());
        }
    
    }
    

    将产生以下输出:

    annotationDefault
    null
    

    选项 #3 - 在 Unmarshaller 上指定 XML 架构以强制验证

    使用 MOXy 或任何 JAXB 实现,您可以在 Unmarshaller 上设置 XML 模式以验证输入:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 2015-03-27
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2011-03-18
      • 2019-08-30
      相关资源
      最近更新 更多