2012-12-13 26 views

回答

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

要使用莫西爲您的JAXB提供你需要包括一個名爲在同一個包jaxb.properties爲您的域模型如下條目:

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

XML Schema

下面是th e對應於域模型的XML模式。請注意0​​元素不具有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屬性的等價物。

:如果你有興趣在此行爲,請通過下面的鏈接進入一個增強請求
相關問題