【问题标题】:Equivalent to @XmlElement.required in @XmlPath in EclipseLink MOXy等效于 EclipseLink MOXy 中 @XmlPath 中的 @XmlElement.required
【发布时间】:2012-12-01 01:15:00
【问题描述】:

如何在EclipseLink MOXy 2.4.1版本中使用@XmlPath注解实现@XmlElement.required标志?

【问题讨论】:

    标签: jaxb eclipselink moxy


    【解决方案1】:

    您可以使用@XmlElement(required=true)@XmlPath 注释来指定叶元素是必需的。

    客户

    下面是一个示例域模型,其中两个字段映射为@XmlPath,其中一个我也使用了@XmlElement(required=true)

    package forum13854920;
    
    import javax.xml.bind.annotation.*;
    import org.eclipse.persistence.oxm.annotations.XmlPath;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Customer {
    
        @XmlPath("personal-info/first-name/text()")
        private String firstName;
    
        @XmlPath("personal-info/last-name/text()")
        @XmlElement(required=true)
        private String lastName;
    
    }
    

    jaxb.properties

    要将 MOXy 用作您的 JAXB 提供程序,您需要在与域模型相同的包中包含一个名为 jaxb.properties 的文件,其中包含以下条目:

    javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
    

    XML 架构

    下面是与域模型对应的 XML 模式。注意last-name 元素没有minOccurs="0"

    <?xml version="1.0" encoding="UTF-8"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
       <xsd:complexType name="customer">
          <xsd:sequence>
             <xsd:element name="personal-info" minOccurs="0">
                <xsd:complexType>
                   <xsd:sequence>
                      <xsd:element name="first-name" type="xsd:string" minOccurs="0"/>
                      <xsd:element name="last-name" type="xsd:string"/>
                   </xsd:sequence>
                </xsd:complexType>
             </xsd:element>
          </xsd:sequence>
       </xsd:complexType>
    </xsd:schema>
    

    演示

    以下演示代码可用于生成 XML 架构。

    package forum13854920;
    
    import java.io.IOException;
    import javax.xml.bind.*;
    import javax.xml.transform.Result;
    import javax.xml.transform.stream.StreamResult;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Customer.class);
    
            jc.generateSchema(new SchemaOutputResolver() {
    
                @Override
                public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException {
                    StreamResult result = new StreamResult(System.out);
                    result.setSystemId(suggestedFileName);
                    return result;
                }
    
            });
        }
    
    }
    

    目前,EclipseLink JAXB (MOXy) 没有与路径其他段的 @XmlElement 注释上的 required 属性等效的属性。如果您对此行为感兴趣,请使用以下链接输入增强请求:

    【讨论】:

      猜你喜欢
      • 2012-02-02
      • 2012-01-14
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 2014-12-23
      相关资源
      最近更新 更多