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

8
我正在使用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


只需在内容中使用@XmlValue添加一个空字符串。 - MeGoodGuy
3个回答

3
如果您已经从XSD生成了类,那么您也将生成ObjectFactory类。如果没有,请参考此处了解如何生成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();

这将会给你所需的输出。

0

这种行为取决于实现。我遇到了相反的问题(我需要自闭合标签),我是用this的方式解决的。
您可以尝试使用此版本的marshal()或修改链接答案中的代码。


-1
问题已解决, 要强制关闭标签,只需将空字符串作为该标签的值添加即可! 您可以使用 @XmlValue 来实现:
public class closedTag {

    @XmlValue
    private String content;


    public closedTag() {
        this.content = "";
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接