Xml处理——获取Xml格式数据
发布时间:2020-12-16 08:49:31 所属栏目:百科 来源:网络整理
导读:转换为XML格式 public String asXml (Object obj) throws Exception { JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, t
转换为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");
// 去掉xml头
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;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |