对于没有@XmlRootElement注释的类,我们有什么方法可以解组?或者我们是否有义务输入注释?
例如:
public class Customer {
private String name;
private int age;
private int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
让正确注释的类的解组代码如下:
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer);
} catch (JAXBException e) {
e.printStackTrace();
}
忽略细节。
答案 0 :(得分:28)
以下代码用于编组和取消联合@XmlRootElement
public static void main(String[] args) {
try {
StringWriter stringWriter = new StringWriter();
Customer c = new Customer();
c.setAge(1);
c.setName("name");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(new JAXBElement<Customer>( new QName("", "Customer"), Customer.class, null, c), stringWriter);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
InputStream is = new ByteArrayInputStream(stringWriter.toString().getBytes());
JAXBElement<Customer> customer = (JAXBElement<Customer>) jaxbUnmarshaller.unmarshal(new StreamSource(is),Customer.class);
c = customer.getValue();
} catch (JAXBException e) {
e.printStackTrace();
}
}
以上代码仅在您在Customer类上添加@XmlAccessorType(XmlAccessType.PROPERTY)
或将所有属性设为私有时才有效。
答案 1 :(得分:2)
如果无法将XmlRootElement添加到现有bean,您还可以创建一个holder类,并使用注释将其标记为XmlRootElement。示例如下: -
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class CustomerHolder
{
private Customer cusotmer;
public Customer getCusotmer() {
return cusotmer;
}
public void setCusotmer(Customer cusotmer) {
this.cusotmer = cusotmer;
}
}
答案 2 :(得分:0)
我使用以下通用解决方案:
public static <T> String objectToXmlStringNoRoot(T obj, Class<T> objClass, final String localPart) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(objClass);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// To format XML
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//If we DO NOT have JAXB annotated class
JAXBElement<T> jaxbElement = new JAXBElement<>(new QName("", localPart), objClass, obj);
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(jaxbElement, sw);
return sw.toString();
}