繁体   English   中英

如果在xml文件中通过java中的jaxb unmarshalling不存在该元素,如何设置元素的默认值

[英]how to set default value for element if that element is absent in xml file through jaxb unmarshalling in java

问题是我想为input.xml文件中缺少的“name”元素设置一个默认值。如何通过jaxb实现这一点?我不想通过java模型来实现。 有没有办法通过shema或jaxb获得它。 以下是代码:

1. customer.xsd

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="customer">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="name" type="stringMaxSize5" minOccurs="0" default="ss"/>
                <xs:element name="phone-number" type="xs:integer" minOccurs="0" default="200" />
             </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:simpleType name="stringMaxSize5">
        <xs:restriction base="xs:string">
            <xs:maxLength value="5"/>
        </xs:restriction>
    </xs:simpleType>

</xs:schema> 

2. Customer.model

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "name",
    "phoneNumber"
})
@XmlRootElement(name = "customer")
public class Customer {

    @XmlElement(defaultValue = "ss")
    protected String name;
    @XmlElement(name = "phone-number", defaultValue = "200")
    protected BigInteger phoneNumber;
    public String getName() {
        return name;
    }
    public void setName(String value) {
        this.name = value;
    }
    public BigInteger getPhoneNumber() {
        return phoneNumber;
    }
    public void setPhoneNumber(BigInteger value) {
        this.phoneNumber = value;
    }
}

3. input.xml

<customer>

</customer>

使用以下代码进行解组:

SchemaFactory sf =SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("customer.xsd"));

JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setSchema(schema);
Customer customer = (Customer) unmarshaller.unmarshal(new File("input.xml"));
System.out.println(customer.getName() + "   " + customer.getPhoneNumber());

通过运行这个我得到名称的空值,如果我使用下面的input.xml文件与“name”元素,然后我得到名称字段的默认值。

input.xml file:
<customer><name/></customer>

那么,如何通过jaxb设置缺失元素的默认值?

原因是您的XML文档缺少元素。 请参阅JAXB指南

当类具有带默认值的element属性时,如果您正在读取的文档缺少该元素 ,则unmarshaller不会使用默认值填充该字段。 相反, 当元素存在但内容丢失时 ,unmarshaller会填充字段

试试这个输入文件

<customer>
    <name/>
    <phone-number/>
</customer>

暂无
暂无

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

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