JAXB 避免保存默认值
有没有办法让 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 配置文件,并使其具有更好的可读性和更小的尺寸。
提前致以问候和感谢。
Is there any way to make JAXB not save fields which values are the default values specified in the @Element annotations, and then make set the value to it when loading elements from XML that are null or empties? An example:
class Example
{
@XmlElement(defaultValue="default1")
String prop1;
}
Example example = new Example();
example.setProp1("default1");
jaxbMarshaller.marshal(example, aFile);
Should generate:
<example/>
And when loading
Example example = (Example) jaxbUnMarshaller.unmarshal(aFile);
assertTrue(example.getProp1().equals("default1"));
I am trying to do this in order to generate a clean XML configuration file, and make it better readable and smaller size.
Regars and thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过利用
XmlAccessorType(XmlAccessType.FIELD)
并将逻辑放入 get/set 方法中来执行类似以下操作:示例
演示
输出
了解更多信息
You could do something like the following by leveraging
XmlAccessorType(XmlAccessType.FIELD)
and putting logic in the get/set methods:Example
Demo
Output
For More Information
对于编程解决方案,还有很好的旧 Apache commons XmlSchema 您可以使用 XmlSchemaElement.getDefaultValue() 检查默认值,
因此,
您应该能够执行您需要的操作。最终没有尝试过,因为我需要一个更直接的解决方案,但我希望这会有所帮助。
For a programmatic solution, there's also good old Apache commons XmlSchema and you can check against the default value with XmlSchemaElement.getDefaultValue()
So with something like
you should be able to do what you need. Haven't tried it out in the end, because I needed a more direct solution, but I hope that helps.