相当于EclipseLink MOXy中@XmlPath中的@ XmlElement.required

时间:2012-12-13 07:20:42

标签: jaxb eclipselink moxy

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

1 个答案:

答案 0 :(得分: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)在路径的其他段的required注释上没有等效的@XmlElement属性。如果您对此行为感兴趣,请使用以下链接输入增强请求:

相关问题