xml格式内容转换成字符串

将xml格式的内容,压缩成一行字符串

public void fun1() throws JDOMException, IOException {
        SAXBuilder oBuilder = new SAXBuilder();
        File oFile = new File(path);
        Document oXmlDoc = oBuilder.build(oFile);
        String xmlString="";
        Format format = Format.getPrettyFormat();
        format.setEncoding("UTF-8");
        XMLOutputter xmlout = new XMLOutputter(format);
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        xmlout.output(oXmlDoc, bo);
        xmlString = bo.toString();
        BufferedReader reader = new BufferedReader(new StringReader(xmlString));
        StringBuffer result = new StringBuffer();
        try {
            String line;
            while ((line = reader.readLine()) != null)
                result.append(line.trim());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        xmlString = result.toString();
        boolean xmlHeader = false;
        if (!xmlHeader) {
            xmlString = xmlString.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
        }
        System.out.println("jdom解析xml文件转换字符串:");
        System.out.println(xmlString);
    }

 

posted @ 2021-08-27 15:56  kevinFeng  阅读(1829)  评论(0编辑  收藏  举报