我使用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
答案 0 :(得分:2)
如果您已从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();
这将为您提供所需的输出。
答案 1 :(得分:0)
此行为取决于实现。我偶然发现了相反的问题(我需要自动关闭标记)并且我以this方式解决了。
您可以尝试使用this version of marshal()
或修改链接答案中的代码。
答案 2 :(得分:0)
I know both are equals but he is not agree with me.
他错了。作为一名软件专业人士,您必须学习如何告诉客户他的错误。如果您是电工并且您的客户要求您以不正确的方式连接开关,您会告诉他作为专业人员您必须遵守行业标准。
答案 3 :(得分:0)
问题解决了, 要强制关闭标签,只需添加一个空字符串作为此标签的值即可! 您可以使用@XmlValue进行操作:
public class closedTag {
@XmlValue
private String content;
public closedTag() {
this.content = "";
}
}