File fileinput = new File("src/main/resources/.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fileinput); // 方法1:将xml文件转化为String // StringWriter sw = new StringWriter(); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); // transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // transformer.transform(new DOMSource(doc), new StreamResult(sw)); // System.out.println(sw); //方法2 DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); // 将转换过的xml的String 样式打印到控制台 // System.out.println(writer);
05-29
10-18