原文: https://howtodoinjava.com/xml/xml-to-string-write-xml-file/

Java 示例读取 XML 文件打印 XML 字符串进行控制台,或将 XML 写入文件

1)将 XML 转换为字符串

要将 XML 对象(即org.w3c.dom.Document)转换为字符串,您需要以下类:

1.1)将 XML 打印到控制台或日志文件

  1. private static void writeXmlDocumentToXmlFile(Document xmlDocument)
  2. {
  3. TransformerFactory tf = TransformerFactory.newInstance();
  4. Transformer transformer;
  5. try {
  6. transformer = tf.newTransformer();
  7. // Uncomment if you do not require XML declaration
  8. // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  9. //A character stream that collects its output in a string buffer,
  10. //which can then be used to construct a string.
  11. StringWriter writer = new StringWriter();
  12. //transform document to string
  13. transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer));
  14. String xmlString = writer.getBuffer().toString();
  15. System.out.println(xmlString); //Print to console or logs
  16. }
  17. catch (TransformerException e)
  18. {
  19. e.printStackTrace();
  20. }
  21. catch (Exception e)
  22. {
  23. e.printStackTrace();
  24. }
  25. }

1.2)将 XML 写入文件

  1. private static void writeXmlDocumentToXmlFile(Document xmlDocument, String fileName)
  2. {
  3. TransformerFactory tf = TransformerFactory.newInstance();
  4. Transformer transformer;
  5. try {
  6. transformer = tf.newTransformer();
  7. //Uncomment if you do not require XML declaration
  8. //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  9. //Write XML to file
  10. FileOutputStream outStream = new FileOutputStream(new File(fileName));
  11. transformer.transform(new DOMSource(xmlDocument), new StreamResult(outStream));
  12. }
  13. catch (TransformerException e)
  14. {
  15. e.printStackTrace();
  16. }
  17. catch (Exception e)
  18. {
  19. e.printStackTrace();
  20. }
  21. }

2)从文件读取 XML

将 XML 从.xml文件读取到Document对象的示例。

  1. private static Document convertXMLFileToXMLDocument(String filePath)
  2. {
  3. //Parser that produces DOM object trees from XML content
  4. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  5. //API to obtain DOM Document instance
  6. DocumentBuilder builder = null;
  7. try
  8. {
  9. //Create DocumentBuilder with default configuration
  10. builder = factory.newDocumentBuilder();
  11. //Parse the content to Document object
  12. Document xmlDocument = builder.parse(new File(filePath));
  13. return xmlDocument;
  14. }
  15. catch (Exception e)
  16. {
  17. e.printStackTrace();
  18. }
  19. return null;
  20. }

3)完整的例子

用于运行示例的完整代码。

  1. package com.howtodoinjava.demo;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.StringWriter;
  5. import javax.xml.parsers.DocumentBuilder;
  6. import javax.xml.parsers.DocumentBuilderFactory;
  7. import javax.xml.transform.Transformer;
  8. import javax.xml.transform.TransformerException;
  9. import javax.xml.transform.TransformerFactory;
  10. import javax.xml.transform.dom.DOMSource;
  11. import javax.xml.transform.stream.StreamResult;
  12. import org.w3c.dom.Document;
  13. public class XmlToStringExample
  14. {
  15. public static void main(String[] args)
  16. {
  17. final String xmlFilePath = "employees.xml";
  18. //Use method to convert XML string content to XML Document object
  19. Document xmlDocument = convertXMLFileToXMLDocument( xmlFilePath );
  20. //Write to file or print XML
  21. writeXmlDocumentToXmlFile(xmlDocument, "newEmployees.xml");
  22. }
  23. private static Document convertXMLFileToXMLDocument(String filePath)
  24. {
  25. //Parser that produces DOM object trees from XML content
  26. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  27. //API to obtain DOM Document instance
  28. DocumentBuilder builder = null;
  29. try
  30. {
  31. //Create DocumentBuilder with default configuration
  32. builder = factory.newDocumentBuilder();
  33. //Parse the content to Document object
  34. Document xmlDocument = builder.parse(new File(filePath));
  35. return xmlDocument;
  36. }
  37. catch (Exception e)
  38. {
  39. e.printStackTrace();
  40. }
  41. return null;
  42. }
  43. private static void writeXmlDocumentToXmlFile(Document xmlDocument, String fileName)
  44. {
  45. TransformerFactory tf = TransformerFactory.newInstance();
  46. Transformer transformer;
  47. try {
  48. transformer = tf.newTransformer();
  49. // Uncomment if you do not require XML declaration
  50. // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  51. //Print XML or Logs or Console
  52. StringWriter writer = new StringWriter();
  53. transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer));
  54. String xmlString = writer.getBuffer().toString();
  55. System.out.println(xmlString);
  56. //Write XML to file
  57. FileOutputStream outStream = new FileOutputStream(new File(fileName));
  58. transformer.transform(new DOMSource(xmlDocument), new StreamResult(outStream));
  59. }
  60. catch (TransformerException e)
  61. {
  62. e.printStackTrace();
  63. }
  64. catch (Exception e)
  65. {
  66. e.printStackTrace();
  67. }
  68. }
  69. }

输入文件。

  1. <employees>
  2. <employee id="101">
  3. <name>Lokesh Gupta</name>
  4. <title>Author</title>
  5. </employee>
  6. <employee id="102">
  7. <name>Brian Lara</name>
  8. <title>Cricketer</title>
  9. </employee>
  10. </employees>

输出文件。

  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  2. <employees>
  3. <employee id="101">
  4. <name>Lokesh Gupta</name>
  5. <title>Author</title>
  6. </employee>
  7. <employee id="102">
  8. <name>Brian Lara</name>
  9. <title>Cricketer</title>
  10. </employee>
  11. </employees>

将我的问题放在评论部分。

学习愉快!