转换为XML格式
public String asXml(Object obj) throws Exception {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
return writer.toString();
}
将XML注入到相应的Bean中
public Object xmlToBean(Class<?> cl, String xml) {
JAXBContext jc;
try {
jc = JAXBContext.newInstance(cl);
Unmarshaller unmar = jc.createUnmarshaller();
return unmar.unmarshal(new StringReader(xml));
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
获取子元素集合
public Map<String, String> getElementText(Element elt) {
Map<String, String> key = new HashMap<String, String>();
for (@SuppressWarnings("rawtypes")
Iterator iter = elt.elementIterator(); iter.hasNext();) {
Element e = (Element) iter.next();
key.put(e.getName(), e.asXML());
}
return key;
}
获取根元素
public Element getRootElement(String xml) {
Document doc;
try {
doc = DocumentHelper.parseText(xml);
Element rootElt = doc.getRootElement();
return rootElt;
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}