views:

28

answers:

2

I want to know a data structure for storing values of tags. My XML structure is :

<personaldetails>
    <name>Michael</name>
    <age>28</age>
    <gender>Male</gender>
    <address>123 Streeet 7</address>
    <country>India</country>
    <pincode> 1234877</pincode>
    <contactno>35646445</contactno>
    <emailid>[email protected]</emailid>
</personaldetails>

I want to store the values at a single place using data structure.Presently i am using setter and getter methods for retrieving values which is making my code large. Can someone suggest something?

+1  A: 

Getters and setters on an object have the advantage of type safety. For example if you tried to write the code getContactN then the compiler would give you an error. So although it might make your code long, getters and setters are good.

An alternative would be to use a map e.g. Map<String,String> to store the values. This is more general - you can insert whatever key you like - and is less code, however it doesn't give you the static analysis benefits of getters and setters. If you mis-spell something you will only discover it when you execute that bit of code - and if it's in an if the code might not always get executed and you might miss it.

There would also be performance differences between using getters/setters and a map, however, i imagine in 99% of applications they would be irrelevant so it's not worth pointing out here. If that code becomes a bottleneck you could put timings in to see which approach is better - but do that only if you can verify you have performance problems in this area, otherwise just use whichever technique is more maintainable and easier for you.

Adrian Smith
Thanx a lot Adrian....But my XML is way too long and making getter setter for each tag is quite large though Easy!!!! I want to use Maps but I am not sure as of now whether code will have if conditions or not
shaireen
A: 

I would recommend you avoid reinventing the wheel by writing your own "container" classes. Instead you could consider generating your Java classes directly from your XML schema using a tool such as xjc, which ships with the JDK. There is a massive advantage in this approach - You do not have to concern yourself with any explicit parsing of XML and the JAXB code will also validate your XML content.

More info on using JAXB here.

EDIT: I only just spotted the Android tag and I confess I'm not sure whether the javax.xml.bind package ships with the JDK for Android devices. However, googling for "xml binding android" seemed to bring up a number of third party tools you could consider.

Adamski