首页 文章

JAXB默认属性值

提问于
浏览
9

我正在使用JAXB注释从我的类生成xsd模式 .

带参数defaultValue的注释@XmlElement设置element的默认值 . 是否可以为@XmlAttribute设置默认值?

附:我检查了xsd语法是否允许属性的默认值

3 回答

  • 4

    可能要检查一下:Does JAXB support default schema values?

    说实话,我不知道为什么标准JAXB中没有属性默认选项 .

  • 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中 .

相关问题