企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Java XML 转换为字符串 – 将 XML 对象写入文件的示例 > 原文: [https://howtodoinjava.com/xml/xml-to-string-write-xml-file/](https://howtodoinjava.com/xml/xml-to-string-write-xml-file/) **Java 示例读取 XML 文件**,**打印 XML 字符串**进行控制台,或**将 XML 写入文件**。 ## 1)将 XML 转换为字符串 要将 XML 对象(即[`org.w3c.dom.Document`](https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/Document.html))转换为字符串,您需要以下类: * [`javax.xml.transform.Transformer`](https://docs.oracle.com/javase/10/docs/api/javax/xml/transform/Transformer.html):此类的实例可以使用其`transform()`方法将源树转换为结果树。 * [`javax.xml.transform.TransformerFactory`](https://docs.oracle.com/javase/10/docs/api/javax/xml/transform/TransformerFactory.html):创建`Transformer`实例的工厂。 * [`javax.xml.transform.dom.DOMSource`](https://docs.oracle.com/javase/10/docs/api/javax/xml/transform/dom/DOMSource.html):文档树(DOM)树形式的源树。 * [`javax.xml.transform.stream.StreamResult`](https://docs.oracle.com/javase/10/docs/api/javax/xml/transform/dom/DOMSource.html):转换结果树的持有人,可以是 XML,纯文本,HTML 或其他某种形式的标记。 #### 1.1)将 XML 打印到控制台或日志文件 ```java 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(); } } ``` #### 1.2)将 XML 写入文件 ```java 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(); } } ``` ## 2)从文件读取 XML 将 XML 从`.xml`文件读取到`Document`对象的示例。 ```java 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; } ``` ## 3)完整的例子 用于运行示例的完整代码。 ```java 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(); } } } ``` 输入文件。 ```java <employees> <employee id="101"> <name>Lokesh Gupta</name> <title>Author</title> </employee> <employee id="102"> <name>Brian Lara</name> <title>Cricketer</title> </employee> </employees> ``` 输出文件。 ```java <?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> ``` 将我的问题放在评论部分。 学习愉快!