String转XML

 /**
     * 
     * 格式化String为Xml
     * 
     * @param inputXML
     * @return
     * @throws Exception
     */
    public static String formatXml(String inputXML) throws Exception {
        String xml = null;
        SAXReader reader = new SAXReader();
        XMLWriter writer = null;
        org.dom4j.Document document = reader.read(new StringReader(inputXML));
        try {
            if (document != null) {
                StringWriter stringWriter = new StringWriter();
                OutputFormat format = OutputFormat.createPrettyPrint();
                format.setNewLineAfterDeclaration(false);
                writer = new XMLWriter(stringWriter, format);
                writer.write(document);
                writer.flush();
                xml = stringWriter.getBuffer().toString();
            }
        } finally {
            if (writer != null) {
                try {
                    writer.close();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return xml;
    }

 

posted @ 2018-04-03 11:42  喻雨晨  阅读(5255)  评论(0编辑  收藏  举报