JAXB - 如何在没有标头的情况下封送 java 对象



我正在尝试封送一个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;
}

如何删除它?

提前谢谢。

我已经用

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")

相关内容

最新更新