jaxb-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>
nillable
属性并将其值设置为
true
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "currencyCode", "discountValue", "setPrice" })
@XmlRootElement(name = "countryData")
public class CountryData {
@XmlElement(nillable=true)
protected String currencyCode;
@XmlElement(nillable=true)
protected String discountValue;
@XmlElement(nillable=true)
protected String setPrice;
// getters and setters
}
输出
<currencyCode>GBP</currencyCode>
<discountValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<setPrice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
null
(默认实例字段值):
protected String discountValue;
protected String setPrice;
标签关闭:
<discountValue/>
<setPrice/>
.replaceAll("<\w+></\\1>","<$1/>")