有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果xml文件中缺少元素,如何在java中通过jaxb解组为该元素设置默认值

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

1。顾客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。顾客型号

@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。输入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());

通过运行此命令,我将获得名称的空值,如果我使用下面的输入。带有“name”元素的xml文件,然后我得到name字段的默认值

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

那么,如何通过jaxb为缺少的元素设置默认值呢


共 (1) 个答案

  1. # 1 楼答案

    原因是您的XML文档缺少元素。见JAXB guide

    When a class has an element property with the default value, and if the document you are reading is missing the element, then the unmarshaller does not fill the field with the default value. Instead, the unmarshaller fills in the field when the element is present but the content is missing

    请尝试此输入文档

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