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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值