In this tutorial we are going to see how to convert XML file into properties using Java
1. Create project called JavaXML.
2. Create package called com.javatutorialscorner.xml
3. Create java class called XMLToProperty under com.javatutorialscorner.xml
XMLToProperty.java
package com.javatutorialscorner.xml;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
public class XMLToProperty {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties properties = null;
InputStream inputStream = null;
try {
properties = new Properties();
inputStream = new FileInputStream("C:\\jtc\\log4j.xml");
properties.loadFromXML(inputStream);
String rootLogger = properties.getProperty("log4j.rootLogger");
System.out.println("Root logger : " + rootLogger);
String appender = properties.getProperty("log4j.appender.HTML");
System.out.println("Appender : " + appender);
} catch (InvalidPropertiesFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In above program loadFromXML() methods loads xml content into property instance getProperty() property method used to get property using key.The log4j.xml file contains following content
log4j.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Log4j XML</comment>
<entry key="log4j.rootLogger">DEBUG, HTML</entry>
<entry key="log4j.appender.HTML">org.apache.log4j.FileAppender</entry>
<entry key="logFile">C:/log</entry>
<entry key="log4j.appender.HTML.File">${logFile}/javatutorialscorner.html</entry>
<entry key="log4j.appender.HTML.layout">org.apache.log4j.HTMLLayout</entry>
<entry key="log4j.appender.HTML.layout.Title">Java Tutorials Corner - Log4j HTML Layout Example</entry>
</properties>
Now we can run the program see the following output in console.
Root logger : DEBUG, HTML
Appender : org.apache.log4j.FileAppender
0 comments:
Post a Comment