JAXB - 如何在没有标题的情况下编组java对象

时间:2017-08-16 12:59:18

标签: java xml jaxb marshalling

我试图编组java对象,但我想删除Jaxb引入的标头。

对象

@XmlRootElement
public class FormElement implements Serializable {
    private String id;
    private String name;
    private Integer order;
}

预期输出:

<element>
    <id>asd</id>
    <name>asd</name>
    <order>1</order>
</element>

我的输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<formElement>
  <id>asd</id>
  <name>asd</name>
  <order>1</order>
</formElement>

我的元帅方法:

public String marshal() {
        JAXBContext context;
        try {
            context = JAXBContext.newInstance(FormElement.class);
            Marshaller marshaller = context.createMarshaller();
            StringWriter stringWriter = new StringWriter();
            marshaller.marshal(this, stringWriter);
            return stringWriter.toString();
        } catch (JAXBException e) {
        }
        return null;
    }

如何删除它?

提前致谢。

1 个答案:

答案 0 :(得分:1)

我用

解决了这个问题

marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

并将(name = "element")添加到@XmlRootElement注释。

正确的方法:

public String marshal() {
    JAXBContext context;
    try {
        context = JAXBContext.newInstance(FormElement.class);
        Marshaller marshaller = context.createMarshaller();
        StringWriter stringWriter = new StringWriter();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        marshaller.marshal(this, stringWriter);
        return stringWriter.toString();
    } catch (JAXBException e) {
        String mess = "Error marshalling FormElement " + e.getMessage()
                + (e.getCause() != null ? ". " + e.getCause() : " ");
        System.out.println(mess);
    }
    return null;
}

正确的注释:

@XmlRootElement(name = "element")