您的位置:首页 > 编程语言 > Java开发

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

2014-03-31 13:45 267 查看
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.
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: