2011-10-26 115 views
8

我使用JAXB注释从我的类生成xsd模式。JAXB默认属性值

带参数defaultValue的Annotation @XmlElement设置元素的默认值。 是否可以为@XmlAttribute设置默认值?

P.S.我检查了XSD语法允许属性

+1

什么...注释有效地没有一些defaultValue键。其实我很惊讶。 –

+0

已经讨论过元素的默认值[here](http://stackoverflow.com/questions/371127) - 也许会帮助你获得属性。 –

回答

0

当您从xsd生成类,并在其中定义一个具有默认值的属性时,那么jaxb将生成一个if子句,它将检查空值,如果是,将返回默认值。

0

对于XML属性,默认值进入getter方法。

例如

customer.xsd

<?xml version="1.0" encoding="UTF-8"?> 
<schema xmlns="http://www.w3.org/2001/XMLSchema"> 
    <element name="Customer"> 
     <complexType> 
      <sequence> 
       <element name="element" type="string" maxOccurs="1" minOccurs="0" default="defaultElementName"></element> 
      </sequence> 
      <attribute name="attribute" type="string" default="defaultAttributeValue"></attribute> 
     </complexType> 
    </element> 
</schema> 

它将产生象下面类。

@XmlRootElement(name = "Customer") 
public class Customer { 

    @XmlElement(required = true, defaultValue = "defaultElementName") 
    protected String element; 
    @XmlAttribute(name = "attribute") 
    protected String attribute; 

    ...... 

    public String getAttribute() { 
     //here the default value is set. 
     if (attribute == null) { 
      return "defaultAttributeValue"; 
     } else { 
      return attribute; 
     } 
    } 

创建的样本XML阅读

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Customer><element/></Customer> 

当我们在主类编写逻辑马歇尔。

File file = new File("...src/com/testdefault/xsd/CustomerRead.xml"); 
      JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); 

      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 
      Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file); 
      System.out.println(customer.getElement()); 
      System.out.println(customer.getAttribute()); 

这将打印在控制台。 defaultElementName defaultAttributeValue

P.S - :要获取元素的默认值,需要将元素的空白副本放入正在编组的xml中。