读取 XML 文件和打印 XML 字符串以控制或将 XML 写入文件的 Java 示例。
转换 XML 对象即 org.w3c.dom.Document
成字符串,你需要以下类:
javax.xml.transform.Transformer
:此类的实例可以使用它的 transform()
方法将源树转换为结果树。javax.xml.transform.TransformerFactory
:创建 Transformer
实例的工厂。javax.xml.transform.dom.DOMSource
:文档对象模型 (DOM) 树形式的源代码树。javax.xml.transform.stream.StreamResult
:转换结果树的持有者,它可以是 XML、纯文本、HTML 或一些其他形式的标记。private static void writeXmlDocumentToXmlFile(Document xmlDocument) { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try { transformer = tf.newTransformer(); // Uncomment if you do not require XML declaration // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //A character stream that collects its output in a string buffer, //which can then be used to construct a string. StringWriter writer = new StringWriter(); //transform document to string transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer)); String xmlString = writer.getBuffer().toString(); System.out.println(xmlString); //Print to console or logs } catch (TransformerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
private static void writeXmlDocumentToXmlFile(Document xmlDocument, String fileName) { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try { transformer = tf.newTransformer(); //Uncomment if you do not require XML declaration //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //Write XML to file FileOutputStream outStream = new FileOutputStream(new File(fileName)); transformer.transform(new DOMSource(xmlDocument), new StreamResult(outStream)); } catch (TransformerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
将 XML 从 .xml
文件读取到 Document
对象的示例。
private static Document convertXMLFileToXMLDocument(String filePath) { //Parser that produces DOM object trees from XML content DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //API to obtain DOM Document instance DocumentBuilder builder = null; try { //Create DocumentBuilder with default configuration builder = factory.newDocumentBuilder(); //Parse the content to Document object Document xmlDocument = builder.parse(new File(filePath)); return xmlDocument; } catch (Exception e) { e.printStackTrace(); } return null; }
用于运行示例的完整代码。
package com.howtodoinjava.demo; import java.io.File; import java.io.FileOutputStream; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class XmlToStringExample { public static void main(String[] args) { final String xmlFilePath = "employees.xml"; //Use method to convert XML string content to XML Document object Document xmlDocument = convertXMLFileToXMLDocument( xmlFilePath ); //Write to file or print XML writeXmlDocumentToXmlFile(xmlDocument, "newEmployees.xml"); } private static Document convertXMLFileToXMLDocument(String filePath) { //Parser that produces DOM object trees from XML content DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //API to obtain DOM Document instance DocumentBuilder builder = null; try { //Create DocumentBuilder with default configuration builder = factory.newDocumentBuilder(); //Parse the content to Document object Document xmlDocument = builder.parse(new File(filePath)); return xmlDocument; } catch (Exception e) { e.printStackTrace(); } return null; } private static void writeXmlDocumentToXmlFile(Document xmlDocument, String fileName) { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try { transformer = tf.newTransformer(); // Uncomment if you do not require XML declaration // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //Print XML or Logs or Console StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer)); String xmlString = writer.getBuffer().toString(); System.out.println(xmlString); //Write XML to file FileOutputStream outStream = new FileOutputStream(new File(fileName)); transformer.transform(new DOMSource(xmlDocument), new StreamResult(outStream)); } catch (TransformerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
输入文件。
<employees> <employee id="101"> <name>Lokesh Gupta</name> <title>Author</title> </employee> <employee id="102"> <name>Brian Lara</name> <title>Cricketer</title> </employee> </employees>
输出文件。
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <employees> <employee id="101"> <name>Lokesh Gupta</name> <title>Author</title> </employee> <employee id="102"> <name>Brian Lara</name> <title>Cricketer</title> </employee> </employees>
地址:https://www.cundage.com/article/xml-to-string-write-xml-file.html