简体   繁体   English

JAXB默认属性值

[英]JAXB default attribute value

I'm using JAXB annotations to generate xsd schema from my classes. 我正在使用JAXB注释从类中生成xsd模式。

Annotation @XmlElement with parameter defaultValue sets default value for element. 参数为defaultValue的注释@XmlElement设置元素的默认值。 Is it possible to set default value for @XmlAttribute? 是否可以为@XmlAttribute设置默认值?

PS I checked that xsd syntax allow default values for attributes PS我检查了xsd语法是否允许属性的默认值

Might wanna check this: Does JAXB support default schema values? 可能要检查以下内容: JAXB是否支持默认架构值?

To be honest, I don't have a clue why there isn't an attribute default option in standard JAXB. 老实说,我不知道为什么标准JAXB中没有属性默认选项。

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

For XML attributes default value goes inside getter method. 对于XML属性,默认值位于getter方法内。

for Example, 例如,

customer.xsd 客户.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>

It will generate class like below. 它将生成如下的类。

@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;
        }
    }

Created Sample XML to read 创建示例XML以读取

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

when we write logic to marshall in our main class. 当我们在主类中编写用于编组的逻辑时。

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());

It will print, in console. 它将在控制台中打印。 defaultElementName defaultAttributeValue defaultElementName defaultAttributeValue

PS -: to get default value of elements you need to have a blank copy of element into xml which is being marshalled. PS-:要获取元素的默认值,您需要将元素的空白副本复制到已编组的xml中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM