Java Convert XML to Properties – Read Properties from XML File

Java example to create .properties file from XML file. This code can be used to read properties key-values from XML file, to be used in the application code.

Properties to XML Example

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

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

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;

public class XMLToProperties 
{
	public static void main(String[] args) throws InvalidPropertiesFormatException, IOException 
	{
		String outPropertiesFile = "application.properties";
		String inXmlFile = "applicationProperties.xml";

		InputStream inStream = new FileInputStream(inXmlFile);			//Input XML File
		OutputStream outStream = new FileOutputStream(outPropertiesFile);	//Output properties File
		
		Properties props = new Properties();
		
		//Load XML file
		props.loadFromXML(inStream);
		
		//Store to properties file
		props.store(outStream, "Converted from applicationProperties.xml");
		
		//Use properties in code
		System.out.println(props.get("input.dir"));			//Prints 'c:/temp/input'
	}
}

Input 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>

Output Properties File

#Converted from applicationProperties.xml
#Mon Jul 23 18:15:00 IST 2018

spring.batch.job.enabled=false
input.dir=c\:/temp/input
spring.main.banner-mode=off

Drop me your questions in comment section.

Happy Learning !!

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial