1. 程式人生 > >[java]JAXB解析XML時預設值處理

[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;

/**
 * <h1>Element default values and unmarshalling</h1> <br>
 * 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 = "<foo/>";
	static String xml2 = "<foo><a/></foo>";
	static String xml3 = "<foo><a>hello</a></foo>";

	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.
	}

}