[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. } }
相关文章推荐
- Jaxb处理java对象和xml之间转换常用的annotation
- jaxb解析xml关于处理list的注解
- JAVA基础学习之XMLCDATA区、XML处理指令、XML约束概述、JavaBean、XML解析(8)
- 使用Java提供的JAXB生成和解析XML
- java 解析xml是报编码异常处理方法
- Java用String 截取方式解析xml文件、处理大xml文件
- java中处理xml数据性能不能大幅提高的根本原因 - 继续追寻高性能xml解析方法
- 【Java】JAXB 处理 复杂XML 与JavaBean 互相转化过程
- 使用JAXB处理JAVA和XML
- java 解析xml是使用dom4j空行以及中文乱码的处理
- 利用oxygen编辑并生成xml文件,并使用JAVA的JAXB技术完成xml的解析
- java xml处理技术一(解析xml和生存xml的技术)
- Webservice_08_JAXB处理java和xml
- Java下3中XML解析 JAXB
- java处理XML三种解析方式比较
- 使用JAXB实现JAVA解析XML (节点大小写和属性的互相转换实例
- 使用Java jaxb处理bean生成xml中一些问题
- jaxb的实例 java解析xml转成javabean
- java生成解析xml的另外两种方法JAXB
- XML解析之JAXB (实现Java对象与XML的相互转换)