Java Convert Properties File to XML File

Java example to create XML file from Properties object or any existing .properties file.

Create XML File from Properties File

To convert properties file into XML file, best way is to use java.util.Properties class. Process is :

  1. Load properties file into java.util.java.util.Properties class object.
  2. Use Properties.storeToXML() method to write the content as XML.
package com.howtodoinjava.demo.xml;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

import javax.xml.stream.XMLStreamException;

public class PropertiesToXML 
{
	public static void main(String[] args) throws XMLStreamException, 
                                     InvalidPropertiesFormatException, IOException 
	{
		String inPropertiesFile = "application.properties";
		String outXmlFile = "applicationProperties.xml";

		InputStream is = new FileInputStream(inPropertiesFile);	//Input file
		OutputStream os = new FileOutputStream(outXmlFile);		//Output file
		
		Properties props = new Properties();
		props.load(is);
		
		props.storeToXML(os, "application.properties","UTF-8");
	}
}

Input Properties File

#Disable batch job's auto start 
spring.batch.job.enabled=false
spring.main.banner-mode=off

#batch input files location
input.dir=c:/temp/input

Output XML File

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
	<comment>application.properties</comment>
	<entry key="input.dir">c:/temp/input</entry>
	<entry key="spring.batch.job.enabled">false</entry>
	<entry key="spring.main.banner-mode">off</entry>
</properties>

Drop me your questions in comment section.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

2 thoughts on “Java Convert Properties File to XML File”

  1. Hello,

    Can you help me generating a XML from XPATHS and value collection or properties.

    e.g. a simple use case – it can be a collection of key value like below

    /root/abc/def/ghi=value1
    /root/abc/def/ggg=value2
    /root/abc/kkk/ggg=value3
    /root/abc/kkk/hhh/iii=value4
    /root/addr/kkk/ggg=value3
    …..

    only root tag is common and inside it can be any hierarchy.

    Java code so appropriate hierarchical xml can be generated

    Thanks

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.