[英]JAXB default attribute value
我正在使用JAXB注释从类中生成xsd模式。
参数为defaultValue的注释@XmlElement设置元素的默认值。 是否可以为@XmlAttribute设置默认值?
PS我检查了xsd语法是否允许属性的默认值
可能要检查以下内容: JAXB是否支持默认架构值?
老实说,我不知道为什么标准JAXB中没有属性默认选项。
当从xsd生成类并在其中定义具有默认值的属性时,jaxb将生成一个if子句,在其中将检查null值,如果是,则将返回默认值。
对于XML属性,默认值位于getter方法内。
例如,
客户.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
PS-:要获取元素的默认值,您需要将元素的空白副本复制到已编组的xml中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.