How to convert XML file to Java Properties file

 

Convert XML file to Java Properties file
In one of our earlier tutorial we have seen how to use Properties class in Java to read property file. Basically property file hold key and corresponding  value part and by just loading those property files we can read application or project related properties which we have configured and also easy to modify those values. 
Same way by using Properties class we can convert XML file to Properties file and also vice-verse (Properties file to XML file). In this tutorial we will see about how to convert XML file to Java Properties file.

Input XML File:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">

<properties>
 <entry key="designation">Software Engineer</entry>
 <entry key="city">Bangalore</entry>
 <entry key="state">Karnataka</entry>
 <entry key="country">India</entry>
</properties>


Java Code to convert XML file to Java Properties file:


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

public class XMLToProperties {
 
 public static void main(String[] args) {
  try{
   Properties property = new Properties();
   InputStream is = new FileInputStream(new File("D://myproperties.xml"));
   property.loadFromXML(is);
   
   String designation = property.getProperty("designation");
   String city = property.getProperty("city");
   String state = property.getProperty("state");
   String country = property.getProperty("country");
   
   System.out.println(designation);
   System.out.println(city);
   System.out.println(state);
   System.out.println(country);
   
  }catch (Exception e) {
   e.printStackTrace();
  }
 } 
}


OUTPUT:


Software Engineer
Bangalore
Karnataka
India


In XML file <properties> and <entry> tag name must be same along with "key" attribute in entry tag which will be identified as key and value properties.  




No comments:
Write comments