Search code examples
androidxml-parsingdata-storage

Reading an xml file in android


I have saved the IP configuration of the server in a xml file in /Simulate/Configuration.xml in my android internal storage

Configuration.xml

<?xml version="1.0"?>

<IPconfig>

<ipAddress>172.**.***.***</ipAddress>
<port>5000</port>

</IPconfig>

The code to access the ipaddress and port number

try {
File sdcard = Environment.getExternalStorageDirectory ();
File FXmlFile = new File (sdcard, "/ Simulate / Configuration.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement (). normalize ();
NodeList nlist = doc.getElementsByTagName ("IPconfig");
for (int temp = 0; temp <nList.getLength (); temp + +) {
Node nNode = nList.item(temp);
if (nNode.getNodeType () == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
SERVERIP= eElement.getAttribute("ipAddress");
System.out.println ("server ip:" + SERVERIP);
SERVERPORT= eElement.getAttribute("port");
System.out.println ("Server port:" + ServerPort);
}
}
}catch (Exception e) {
            e.printStackTrace();
            }

When I print SERVERIP and SERVERPORT both return a null. How can I get the ipaddress and port value from the xml? Any help is appreciated. Also if there is a better way to specify the ipconfig of server.


Solution

  • Answered because of Andrey Voitenkov hint that I had used elements and not attributes :)

    ********EDIT*******
    SERVERIP= eElement.getElementsByTagName("ipAddress").item(0).getTextContent();
    System.out.println("server    ip:"+SERVERIP);
    SERVERPORT= eElement.getElementsByTagName("port").item(0).getTextContent();
    System.out.println("server port:"+SERVERPORT);