编程语言
首页 > 编程语言> > java-如何使用JAXB为XML中的空元素生成结束标记

java-如何使用JAXB为XML中的空元素生成结束标记

作者:互联网

我正在使用JAXB生成XML.但是JAXB会生成一个空的Tag来自我关闭.但是我的客户想要单独的空标签.我知道两者都是平等的,但他不同意我的看法.请任何人提出解决方案.谢谢.

样例代码:

@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,xml,jaxb,java-6,marshalling
来源: https://codeday.me/bug/20191010/1888082.html