Night | Snow

Reading/Writing Settings to Xml in Java

Posted on: November 26th, 2009

Tags: , , , ,

Here’s an easy way to store and retrieve settings or other data from an Xml file.All the settings is set by key/value pairs in an XML file, you can insert and retrieve any key/value. The two major public methods are: get(key,default) and put(key,value) – it’s that simple. You can store String, Integer and Boolean Datatypes.

Here’s how to use the class:

Xml xml = new Xml(System.getProperty("user.home") + "/config.xml","configuration"); // first parameter = xmlFile; second parameter = configuration name
xml.get("key1", "xxx"); // returns xxx if no value is set
xml.get("key2", 11); // the same with an Integer
xml.get("key3", true); // the same with a Boolean Type

xml.put("key4", 5); // stores the value 5
xml.get("key4", 20); // returns 5

xml.writeXml(); // Save all changes

Here’s the main Class:

import java.io.File;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;

/**
 *
 * @author simon
 */

public class Xml {

    private File _xmlFile;
    private Element _config;
    private Document _dom;

    public Xml(String file, String config) {
        _xmlFile = new File(file);
        readXml();
        _config = getConfigElement(config);
    }

    public Object get(String key, Object def) {
        Element e = getElement(key);
        if(e.getChildNodes().getLength()==0){
            return def;
        }
       
        String type = e.getAttribute("type");
        String value = e.getChildNodes().item(0).getNodeValue();

        if(type.indexOf("Integer")>=0){
            return Integer.parseInt(value);
        }else if(type.indexOf("Boolean")>=0){
            return value.equals("true");
        }
        return value;
    }

    public void put(String key, Object value) {
        Element e = getElement(key);
        e.getNodeValue();
        if(e.getChildNodes().getLength()>0){
            e.removeChild(e.getChildNodes().item(0));
        }
        Node n = _dom.createTextNode(value.toString());
        e.appendChild(n);
        e.setAttribute("type", value.getClass().getName());
    }

    public boolean writeXml() {
        try {
            Source source = new DOMSource(_dom);
            Result result = new StreamResult(_xmlFile);
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.transform(source, result);
            return true;
        } catch (Exception ex) {
        }
        return false;
    }

    private Element getElement(String key) {
        NodeList nl = _config.getElementsByTagName(key);
        Element e;
        if (nl != null && nl.getLength() > 0) {
            e = (Element) nl.item(0);
        } else {
            //append element if not exists
            e = _dom.createElement(key);
            _config.appendChild(e);
        }
        return e;
    }

    private Element getConfigElement(String config) {
        Element root = _dom.getDocumentElement();
        NodeList nl = root.getElementsByTagName(config);
        Element e;
        if (nl != null && nl.getLength() > 0) {
            e = (Element) nl.item(0);
        } else {
            //append config if not exists
            e = _dom.createElement(config);
            root.appendChild(e);
        }
        return e;
    }

    private boolean readXml() {
        if (_xmlFile.isFile()) {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder db = dbf.newDocumentBuilder();
                _dom = db.parse(_xmlFile);
                return true;
            } catch (Exception ex) {
            }
        } else {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                DOMImplementation impl = builder.getDOMImplementation();
                _dom = impl.createDocument(null, "Root", null);
                return true;
            } catch (ParserConfigurationException ex) {
            }
        }
        return false;
    }
}

That’s what the Xml File looks like after saving:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <config>
        <key4 type="java.lang.Integer">5</key4>
    </config>
</Root>

Posted in Java | Trackback Url

News

Martin Fischer said:

Client and partner of simra.ch

Wir können Simon Schärer als kompetenter und zuverlässiger Programmierer höchst weiterempfehlen. Er ist nicht nur ein guter Programmierer, sondern auch ein ausgezeichneter Designer.
Danke Developer’s Island

Follow us on Twitter

favorite

I get asked a lot - which SDK should we use for web programming? I recommend Netbeans

my toolbar

Simra GameMP3 playersubscribe to RSSMy delicious bookmarksFacebookTwitterE-mail

No Responses to “Reading/Writing Settings to Xml in Java”

RSS Feed Icon  Subscribe to comments follow-up

Trackbacks/Pingbacks

Leave a reply

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Latest Tweet

loading...