Java – Getting values from xml to .properties file in Java

javapropertiesxml

I have db connection related properties in a .xml file. I want to use the same values in a .properties file. Is it possible to get values from .xml file and set to .properties?


Thanks

Exception while using loadFromXML

Exception in thread "main" java.util.InvalidPropertiesFormatException: org.xml.sax.SAXException: Invalid system identifier: http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd
at java.util.XMLUtils.load(XMLUtils.java:76)
at java.util.Properties.loadFromXML(Properties.java:868)
at com.generalsentiment.test.quartz.CronTriggerExample.run(CronTriggerExample.java:40)
at com.generalsentiment.test.quartz.CronTriggerExample.main(CronTriggerExample.java:117)
Caused by: org.xml.sax.SAXException: Invalid system identifier: http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd
at java.util.XMLUtils$Resolver.resolveEntity(XMLUtils.java:190)
at org.apache.xerces.util.EntityResolverWrapper.resolveEntity(Unknown Source)
at org.apache.xerces.impl.XMLEntityManager.resolveEntity(Unknown Source)
at org.apache.xerces.impl.XMLDocumentScannerImpl$DTDDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at java.util.XMLUtils.getLoadingDoc(XMLUtils.java:102)
at java.util.XMLUtils.load(XMLUtils.java:74)
… 3 more
Java Result: 1

Best Answer

There will be an effort to create an XML property file with the values from your .properties file. The schema of your XML is not specified here; hence assuming it's not in the Java XML properties format.

Java XML property file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Hi</comment>
<entry key="foo">bar</entry>
<entry key="fu">baz</entry>
</properties>

Java code:

import java.util.*;
import java.io.*;

public class LoadSampleXML {
  public static void main(String args[]) throws Exception {
    Properties prop = new Properties();
    FileInputStream fis =
      new FileInputStream("sampleprops.xml");
    prop.loadFromXML(fis);
    prop.list(System.out);
    System.out.println("\nThe foo property: " +
        prop.getProperty("foo"));
  }
}

Sample code referred from here.

Related Topic