java - 如何生成自闭标签使用 JAXB 处理 XML 中的空元素
问题描述
使用forjaxb-api
2.3.1
和 Java 8的示例代码:StringWriter
jaxbMarshaller
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"currencyCode",
"discountValue",
"setPrice"
})
@XmlRootElement(name = "countryData")
public class CountryData {
protected String currencyCode;
protected String discountValue = "";
protected String setPrice = "";
// setters and setters
}
当我将实体编组为 XML 字符串时:
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(countryDataObject, sw);
sw.toString();
如何获得空值的预期结果?
<currencyCode>GBP</currencyCode>
<discountValue/>
<setPrice/>
实际输出:
<currencyCode>GBP</currencyCode>
<discountValue></discountValue>
<setPrice></setPrice>
解决方案
尽管字符串为空,但它们仍包含非空数据并生成结束标记。删除字符串的默认值或将它们设置为null
(默认实例字段值):
protected String discountValue;
protected String setPrice;
标签变为关闭状态:
<discountValue/>
<setPrice/>
推荐阅读
- python-3.x - Python 中的 OOP 快速排序
- html - 屏幕阅读器在到达锚标记时停止阅读段落
- python - Python将单个位附加到字节数组
- php - TCPDF 的 jpeg 和 png 图像质量差
- python - 根据存储在其他 2 个列表中的值对位置列表进行排序
- c++ - 如何将 QPixMap 转换为 QPainterPath,反之亦然?
- html - 表格各部分之间的大填充区域?
- html - 如何在html页面中查找文本坐标
- twitter-bootstrap - Bootstrap 4 Carousel with HTML 5 picture tag instead of img tag works?
- symfony-4.2 - 覆盖 FOUserBundle 后如何编辑 services.yaml