编组时可选的JAXB xml属性

前端之家收集整理的这篇文章主要介绍了编组时可选的JAXB xml属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我使用JAXB编组 java对象时,我得到了xml元素
  1. <error line="12" column="" message="test" />

但我想要xml如下

  1. <error line="12" message="test" />

如果列值为空,那么我需要获取如上所示的xml,否则我需要获取元素中的column属性.

有没有办法得到它?

如果相应的字段/属性包含空字符串值,则只会使用空字符串值对属性进行编组.如果该值为null,则不会对该属性进行编组.

  1. package forum13218462;
  2.  
  3. import javax.xml.bind.annotation.*;
  4.  
  5. @XmlRootElement
  6. public class Root {
  7.  
  8. @XmlAttribute
  9. String attributeNull;
  10.  
  11. @XmlAttribute
  12. String attributeEmpty;
  13.  
  14. @XmlAttribute(required=true)
  15. String attributeNullrequired;
  16.  
  17. }

演示

  1. package forum13218462;
  2.  
  3. import javax.xml.bind.*;
  4.  
  5. public class Demo {
  6.  
  7. public static void main(String[] args) throws Exception {
  8. JAXBContext jc = JAXBContext.newInstance(Root.class);
  9.  
  10. Root root = new Root();
  11. root.attributeNull = null;
  12. root.attributeEmpty = "";
  13. root.attributeNullrequired = null;
  14.  
  15. Marshaller marshaller = jc.createMarshaller();
  16. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
  17. marshaller.marshal(root,System.out);
  18. }
  19.  
  20. }

产量

  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  2. <root attributeEmpty=""/>

猜你在找的XML相关文章