加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何使用JAXB在XML中为空elelemt生成结束标记

发布时间:2020-12-16 00:00:44 所属栏目:百科 来源:网络整理
导读:我正在使用JAXB生成 XML.但是JAXB正在生成一个空标签.但我的客户想要单独的空标签.我知道两者都是平等但他不同意我的看法.请任何人建议解决方案.谢谢. 示例代码: @XmlAccessorType(XmlAccessType.FIELD)@XmlType(name = "",propOrder = { "currencyCode","d
我正在使用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();

这将为您提供所需的输出.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读