编组时可选的JAXB xml属性 [英] optional JAXB xml attribute while marshalling
本文介绍了编组时可选的JAXB xml属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用JAXB编组java对象时,我得到的是xml元素
When I marshal java object using JAXB I am getting below xml element
<error line="12" column="" message="test" />
但我想要xml如下
<error line="12" message="test" />
如果列值为空,那么我需要得到如上所示的xml,否则我需要得到元素中的列属性。
If column value is empty then I need to get the xml as shown above otherwise I need to get the column attribute in the element.
有什么方法可以得到它吗?
Is there any way to get it?
推荐答案
如果相应的字段/属性包含空字符串$ c $,则只会使用空
字符串
值对该属性进行编组处理c>价值。如果该值为null,则不会对该属性进行编组。
An attribute will only be marshalled out with an empty String
value if the corresponding field/property contains a empty String
value. If the value is null the attribute will not be marshalled.
Root
package forum13218462;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Root {
@XmlAttribute
String attributeNull;
@XmlAttribute
String attributeEmpty;
@XmlAttribute(required=true)
String attributeNullRequired;
}
演示
package forum13218462;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Root root = new Root();
root.attributeNull = null;
root.attributeEmpty = "";
root.attributeNullRequired = null;
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root attributeEmpty=""/>
这篇关于编组时可选的JAXB xml属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文