英文:
How to generate self-closing tag <tag/> for empty element in XML using JAXB
问题
使用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 getters
}
当我使用以下代码将实体编组为XML字符串时:
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(countryDataObject, sw);
sw.toString();
如何获得空值的预期结果?
<currencyCode>GBP</currencyCode>
<discountValue/>
<setPrice/>
实际输出:
<currencyCode>GBP</currencyCode>
<discountValue></discountValue>
<setPrice></setPrice>
英文:
A sample code with jaxb-api
2.3.1
and Java 8 using StringWriter
for 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
}
When I marshal the entity to a XML string with:
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(countryDataObject, sw);
sw.toString();
How to get expected result for empty values?
<currencyCode>GBP</currencyCode>
<discountValue/>
<setPrice/>
Actual output:
<currencyCode>GBP</currencyCode>
<discountValue></discountValue>
<setPrice></setPrice>
答案1
得分: 1
<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"/>
英文:
don't initialized the variables. use the nillable
attribute and set it value to 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
}
output
<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"/>
答案2
得分: 0
虽然这些字符串是空的,但它们仍然包含非空数据,并且会生成结束标签。移除字符串的默认值,或将它们设置为 null
(默认实例字段值):
protected String discountValue;
protected String setPrice;
标签会变成闭合形式:
<discountValue/>
<setPrice/>
英文:
Although the strings are empty they still contain non-null data and the end tag is generated. Remove the default values of the strings or set them as null
(a default instance field value):
protected String discountValue;
protected String setPrice;
The tags become closed:
<discountValue/>
<setPrice/>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论