Xml处理——获取Xml格式数据

来源:互联网 发布:rbac java 框架 编辑:程序博客网 时间:2024/05/07 19:36

转换为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;    }
1 0