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

前端之家收集整理的这篇文章主要介绍了Xml处理——获取Xml格式数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

猜你在找的XML相关文章