[英]JAXB Avoid saving default values
是否有任何方法可以使JAXB不保存哪些值是@Element注釋中指定的默認值,然后在從XML加載null或空的元素時將值設置為它? 一個例子:
class Example
{
@XmlElement(defaultValue="default1")
String prop1;
}
Example example = new Example();
example.setProp1("default1");
jaxbMarshaller.marshal(example, aFile);
應該生成:
<example/>
並在加載時
Example example = (Example) jaxbUnMarshaller.unmarshal(aFile);
assertTrue(example.getProp1().equals("default1"));
我試圖這樣做是為了生成一個干凈的XML配置文件,並使其更好的可讀性和更小的尺寸。
提前退位並表示感謝。
您可以通過利用XmlAccessorType(XmlAccessType.FIELD)
並將邏輯放入get / set方法來執行以下操作:
例
package forum8885011;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Example {
private static final String PROP1_DEFAULT = "default1";
private static final String PROP2_DEFAULT = "123";
@XmlElement(defaultValue=PROP1_DEFAULT)
String prop1;
@XmlElement(defaultValue=PROP2_DEFAULT)
Integer prop2;
public String getProp1() {
if(null == prop1) {
return PROP1_DEFAULT;
}
return prop1;
}
public void setProp1(String value) {
if(PROP1_DEFAULT.equals(value)) {
prop1 = null;
} else {
prop1 = value;
}
}
public int getProp2() {
if(null == prop2) {
return Integer.valueOf(PROP2_DEFAULT);
}
return prop2;
}
public void setProp2(int value) {
if(PROP2_DEFAULT.equals(String.valueOf(value))) {
prop2 = null;
} else {
prop2 = value;
}
}
}
演示
package forum8885011;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Example.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Example example = new Example();
example.setProp1("default1");
example.setProp2(123);
System.out.println(example.getProp1());
System.out.println(example.getProp2());
marshaller.marshal(example, System.out);
example.setProp1("FOO");
example.setProp2(456);
System.out.println(example.getProp1());
System.out.println(example.getProp2());
marshaller.marshal(example, System.out);
}
}
產量
default1
123
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<example/>
FOO
456
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<example>
<prop1>FOO</prop1>
<prop2>456</prop2>
</example>
欲獲得更多信息
對於程序化解決方案,還有很好的舊Apache公共XmlSchema ,您可以使用XmlSchemaElement.getDefaultValue()檢查默認值。
有這樣的東西
XmlSchemaElement elem = schema.getElementByName(ELEMENT_QNAME);
String defval = elem.getDefaultValue();
你應該能夠做你需要的。 最后沒有嘗試過,因為我需要更直接的解決方案,但我希望有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.