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

标签 java xml jaxb marshalling java-6

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

相关文章:

java - 将 XML 转换为属于同一模式的不同版本且稍有不同的 XML

java - 如何将 listView 放入 android studio 的 ScrollView 中?

xml - XML 属性中允许的最大字符数是多少?

java - 键盘打开时自定义操作栏隐藏

java - 使用 JAXB 将 XML 子内部节点从 XML 拉到 Java 对象

java - JAXB 接受重复标签

java - 在 Java 中处理运行时异常

java - 关于java中==运算符的问题

java - 在 java shell 上执行 Linux 命令 (mutt) 无法正常工作

java - 如何在JAVA中处理字符串编码(linux操作系统)