我正在使用 JAXB 生成 XML。但是 JAXB 正在生成一个空标签,将其自行关闭。但我的客户想要单独的空标签。我知道两者是平等的,但他不同意我的看法。请任何人提出解决方案。谢谢。
示例代码:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"currencyCode",
"discountValue",
"setPrice",
"spendLowerThreshold",
"spendUpperThreshold",
"discountApportionmentPercent",
"discountApportionmentValue"
})
@XmlRootElement(name = "countryData")
public class CountryData {
protected String currencyCode;
protected String discountValue = "";
protected String setPrice = "";
protected String spendLowerThreshold = "";
protected String spendUpperThreshold = "";
protected String discountApportionmentPercent = "";
protected String discountApportionmentValue = "";
// Setters and Gettres
}
实际输出:
<currencyCode>GBP</currencyCode>
<discountValue/>
<setPrice/>
<spendLowerThreshold/>
<spendUpperThreshold/>
<discountApportionmentPercent>0.0</discountApportionmentPercent>
<discountApportionmentValue/>
预期输出:
<currencyCode>GBP</currencyCode>
<discountValue></discountValue>
<setPrice></setPrice>
<spendLowerThreshold></spendLowerThreshold>
<spendUpperThreshold></spendUpperThreshold>
<discountApportionmentPercent>0.0</discountApportionmentPercent>
<discountApportionmentValue></discountApportionmentValue>
编码代码:
try {
Marshaller marshaller = JAXBContext.newInstance(CountryData.class).createMarshaller();
ByteArrayOutputStream os = new ByteArrayOutputStream();
marshaller.marshal(countryData , os);
log.debug("The PPV request raw XML -> " + os.toString());
} catch (JAXBException e) {
// nothing to do
}
我正在使用 JDK 6.0
最佳答案
如果您从 XSD 生成了类那么您还将生成 ObjectFactory 类。如果没有请引用 here关于如何生成 ObjectFactory 类。
在那之后,你的代码会像--
JAXBContext context;
context = JAXBContext.newInstance(*yourClass*.class);
final ObjectFactory objFactory = new ObjectFactory();
final JAXBElement<YourClass> element = objFactory
.*autoGeneratedmethodfromObjectFactorytogetelement*;
Marshaller marshaller;
marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
final StringWriter stringWriter = new StringWriter();
marshaller.marshal(element, stringWriter);
String message = stringWriter.toString();
这将为您提供所需的输出。
关于java - 如何使用 JAXB 为 XML 中的空元素生成结束标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32448868/