Java XML 到字符串 - 将 XML 对象写入文件示例

位置:首页>文章>详情   分类: Java教程 > 编程技术   阅读(301)   2023-06-26 07:54:18

读取 XML 文件打印 XML 字符串以控制或将 XML 写入文件的 Java 示例。

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>
标签2: Java XML XML Files Java
地址:https://www.cundage.com/article/xml-to-string-write-xml-file.html

相关阅读

读取 XML 文件和打印 XML 字符串以控制或将 XML 写入文件的 Java 示例。 1) 将 XML 转换为字符串 转换 XML 对象即 org.w3c.dom.Document 成字符串...
在 Java 中,XML 用 org.w3c.dom.Document 对象表示。在本 XML 教程中,我们将学习 – 将 XML 字符串转换为 XML 文档 将 XML 文件内容转换为 XML...
在此Java xml 解析器教程中,学习在Java 中使用DOM 解析器读取xml。 DOM 解析器旨在将 XML 作为内存中的对象图(树状结构)进行处理——所谓的“文档对象模型 (DOM)”。...
将 Java 对象写入 XML 的 Java 示例。存储在 Java 对象字段中的信息可以写入 XML 文件 或简单地写入 XML 字符串。 1) 将 Java 对象转换为 XML 字符串 要将...
从 XML 文件创建 .properties 文件的 Java 示例。此代码可用于从 XML 文件中读取属性键值,以在应用程序代码中使用。 XML 示例的属性 要将 XML 文件转换为属性文件,...
学习使用 Java StAX 解析器解析和读取 XML 文件。 StAX(XML 流 API)提供了两种解析 XML 的方法,即基于游标的 API 和基于迭代器的 API。 1) StAX解析器...
学习根据架构 (xsd) 验证 XML,然后将 XML 解组为 Java 对象。如果验证失败,还要学习检查 xml 架构验证期间的验证错误。 更多参考:如何从 JAXB 类生成模式 1. XSD...
从 Properties 对象或任何现有 .properties 文件创建 XML 文件的 Java 示例。 从Properties文件创建 XML 文件 要将Properties文件转换为 X...
Java xpath 示例 读取 XML 文件并解析为 DOM 对象,然后评估 org.w3c.dom.Document 对象上的 xpath 并获得结果以 String 或 NodeList ...
JDOM 解析器 可用于读取 XML、解析 xml 以及在更新 XML 文件内容后写入 XML 文件。它将JDOM2 文档 存储在内存中以读取和修改它的值。 将 XML 文档加载到内存后,JDO...