[java]JAXB解析XML时默认值处理

package test.xml;

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 

Element default values and unmarshalling


* 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. * */ public class JAXBTest { @XmlRootElement static class Foo { private String a = "java default"; public String getA() { return a; } @XmlElement(defaultValue = "jaxb default") public void setA(String a) { this.a = a; } } static String xml1 = ""; static String xml2 = ""; static String xml3 = "hello"; public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Foo.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); Foo foo1 = (Foo) unmarshaller.unmarshal(new StringReader(xml1)); System.out.println(foo1.a); // "java default" Foo foo2 = (Foo) unmarshaller.unmarshal(new StringReader(xml2)); System.out.println(foo2.a); // "jaxb default". The default kicked in. Foo foo3 = (Foo) unmarshaller.unmarshal(new StringReader(xml3)); System.out.println(foo3.a); // "hello". Read from the instance. } }

你可能感兴趣的:([java]JAXB解析XML时默认值处理)