我正在尝试制作一种将POJO对象转换为XML字符串的通用方法。
我正在尝试使用此方法来实现此目标。
public class Util{
public static String jaxbObjectToXML(Object xmlObj) {
String xmlString = "";
try {
JAXBContext context = JAXBContext.newInstance(POJO.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(xmlObj, stringWriter);
xmlString = stringWriter.toString();
} catch (JAXBException e) {
e.printStackTrace();
}
return xmlString;
}
}
现在在
JAXBContext context = JAXBContext.newInstance(**POJO.class**);
行中,我试图使该POJO值通用。就像我可以传递类名,对象或可以完成工作的东西一样。还要在方法中添加适当的参数。
最佳答案
您可以使用以下命令:
@XmlRootElement
public class Util {
@XmlElement
private String name;
@XmlElement
private String description;
public static void main(String[] args) {
Util xmlObj = new Util();
xmlObj.name = "Alex";
xmlObj.description = "Alex Rose";
jaxbObjectToXML(xmlObj, xmlObj.getClass());
}
public static <T> String jaxbObjectToXML(T xmlObj, Class<? extends T> aClass) { {
String xmlString = "";
try {
JAXBContext context = JAXBContext.newInstance(aClass);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(xmlObj, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
return xmlString;
}
}
输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<util>
<name>Alex</name>
<description>Alex Rose</description>
</util>
或
JAXBContext.newInstance(xmlObj.getClass());