1

I am working on an application using Java and XML file to save settings like language..

setting.xml

<?xml version="1.0" encoding="UTF-8"?>
<parametre>
    <param name="Langue" id="1">
        <val>1</val>
    </param>
    <param name="Controle" id="2">
        <val>0</val>
    </param>
</parametre>

this class should read and write from the XML file.

import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class DialXMLFile {

    private static boolean _initialized = false;
    private static boolean _init = false;
    private static Document _docx,_docy;

public static void initlang() {
    if(_initialized) {
        return;
    }

    try {
        File fXmlFile = new File("res/files/strings.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        _docx = dBuilder.parse(fXmlFile);
        _docx.getDocumentElement().normalize();

        _initialized = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void initparam() {
    if(_init) {
        return;
    }

    try {
        File fXmlFile = new File("res/files/setting.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        _docy = dBuilder.parse(fXmlFile);
        _docy.getDocumentElement().normalize();

        _init = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static String readLbl(String name, int lang) {
    if(!_initialized) {
        initlang();
    }

    String res = "";

    try {
        NodeList nList = _docx.getElementsByTagName("lang");
        Node nNode = nList.item(lang);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
            res=eElement.getElementsByTagName(name).item(0).getTextContent();
        }
    } catch (Exception e) {
        res="$ERROR";
        e.printStackTrace();
    }

    return res;
}

public static int readCtrl() {
    if(!_init) {
        initparam();
    }

    int rs = 0;

    try {
        NodeList nparamList = _docy.getElementsByTagName("param");
        Node nparamNode = nparamList.item(1);
        if (nparamNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eparamElement = (Element) nparamNode;
            rs=Integer.parseInt(eparamElement.getElementsByTagName("val").item(0).getTextContent());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return rs;
}

public static int readLang() {
    if(!_init) {
        initparam();
    }

    int rs = 0;

    try {
        NodeList nparamList = _docy.getElementsByTagName("param");
        Node nparamNode = nparamList.item(0);
        if (nparamNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eparamElement = (Element) nparamNode;
            rs=Integer.parseInt(eparamElement.getElementsByTagName("val").item(0).getTextContent());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return rs;
}

public static void writeLang(String i) {
    initparam();
    try {
        NodeList nparamList = _docy.getElementsByTagName("param");
        Node nparamNode = nparamList.item(0);
        if (nparamNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eparamElement = (Element) nparamNode;
            eparamElement.getElementsByTagName("val").item(0).setTextContent(i);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }   
}

public static void writeCtrl(String i) {
    initparam();
    try {
        NodeList nparamList = _docy.getElementsByTagName("param");
        Node nparamNode = nparamList.item(1);
        if (nparamNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eparamElement = (Element) nparamNode;
            eparamElement.getElementsByTagName("val").item(0).setTextContent(i);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

}

but it can't write anything..! note that it read correctly and it do not give any error or exception when excute. thanks for any ideas or help.

Malek Boubakri
  • 820
  • 2
  • 17
  • 36
  • Why is everything `static`? Very bad. Remove all statics and *maybe* make `DialXMLFile` into a [singleton](https://en.wikipedia.org/wiki/Singleton_pattern). *Maybe*. – Andreas Aug 31 '15 at 05:03
  • Why shouldn't use static !?!? – Malek Boubakri Aug 31 '15 at 15:26
  • 1
    Lots of articles on that, e.g. [Why are static variables considered evil?](http://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil) – Andreas Aug 31 '15 at 15:59
  • Ok!! i'll read them all :) but a dont have any other idea. Do you suggest an approach? – Malek Boubakri Aug 31 '15 at 19:09
  • 1
    The caller(s) of the `DialXMLFile` methods should keep an instance of class around, for as long as they need the `Document` fields retained (cached). If the methods are used in varying places of your code, and passing an instance of `DialXMLFile` around is not feasible/convenient, you can make `DialXMLFile` into a singleton. See link in my first comment. – Andreas Aug 31 '15 at 19:36

1 Answers1

1

Your approach is very error prone and not scalable/customizable. If you are looking to read in an XML into your Java code and have access to the values that you set there, I recommend you look at JAXB or a library like fasterxml Jackson. This will let you map XML files into Java objects and back. For example, this would be a start of the implementation with JAXB:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "parametre")
public class Parametre {
    List<Param> params;
}

@XmlType(name = "param")
public class Param {
    @XmlAttribute(name = "required")
    String name;
    String value;
}

You would then have access to the data through normal Java objects.

mvd
  • 2,596
  • 2
  • 33
  • 47