Java XML 转换为字符串 – 将 XML 对象写入文件的示例

Java XML 转换为字符串 – 将 XML 对象写入文件的示例

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

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

1)将 XML 转换为字符串

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

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

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 写入文件

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对象的示例。

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)完整的例子

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

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>

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

学习愉快!