如何使用 JAXB 为 XML 中的空元素生成自关闭标签 <tag/>

问题描述 投票:0回答:3
使用

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>
    
java xml java-8 jaxb marshalling
3个回答
1
投票
不要初始化变量。使用

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"/>
    

0
投票
虽然字符串为空,但它们仍然包含非空数据,并且会生成结束标记。删除字符串的默认值或将它们设置为

null

(默认实例字段值):

protected String discountValue; protected String setPrice;
标签关闭:

<discountValue/> <setPrice/>
    

0
投票
只需更换它们即可:

.replaceAll("<\w+></\\1>","<$1/>")
    
© www.soinside.com 2019 - 2024. All rights reserved.