/** * <b>function:</b>java对象转换成xml文档 * 需要额外的jar包 stax2-api.jar * @author hoojo * @createDate 2010-11-23 下午06:11:21 */@Testpublic void writeObject2Xml() { //stax2-api-3.0.2.jar System.out.println("XmlMapper"); XmlMapper xml = new XmlMapper(); try { //javaBean转换成xml //xml.writeValue(System.out, bean); StringWriter sw = new StringWriter(); xml.writeValue(sw, bean); System.out.println(sw.toString()); //List转换成xml List<AccountBean> list = new ArrayList<AccountBean>(); list.add(bean); list.add(bean); System.out.println(xml.writeValueAsString(list)); //Map转换xml文档 Map<String, AccountBean> map = new HashMap<String, AccountBean>(); map.put("A", bean); map.put("B", bean); System.out.println(xml.writeValueAsString(map)); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}
运行上面的方法,结果如下:
XmlMapperchina-Guangzhouhoojo1hoojo_@126.comchina-Guangzhouhoojo1hoojo_@126.comchina-Guangzhouhoojo1hoojo_@126.comchina-Guangzhouhoojo1hoojo_@126.comchina-Guangzhouhoojo1hoojo_@126.com
看结果,根节点都是unknown 这个问题还没有解决,由于根节点没有转换出来,所有导致解析xml到Java对象,也无法完成。