Click to See Complete Forum and Search --> : How to find maximum value of an element in XML file


daina
02-14-2006, 11:45 PM
Hi

I have an XML file.I want to find the maximum value of an element say userid.So that I can add 1 every time i create new one.Can anyone tell me how to do it.
The code I wrote is

public int check_userid() {
int maxuserid = 0;
try {
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
document = docBuilder.parse(file);

// normalize text representation
document.getDocumentElement().normalize();


NodeList listOfPersons = document.getElementsByTagName("user");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of people : " + totalPersons);

for (int s = 0; s < totalPersons; s++) {

Node firstPersonNode = listOfPersons.item(s);

if (firstPersonNode.getNodeType() Node.ELEMENT_NODE) {

Element firstPersonElement = (Element) firstPersonNode;

// -------
NodeList firstNameList = firstPersonElement.getElementsByTagName("userid");
Element firstNameElement = (Element) firstNameList.item(0);

NodeList textFNList = firstNameElement.getChildNodes();
//System.out.println("Leave id: "+ ((Node) textFNList.item(0)).getNodeValue().trim());
String maxi = textFNList.item(0).getNodeValue().trim();
maxleaveid = Integer.parseInt(maxi);

}
}

} catch (SAXParseException e) {
e.printStackTrace();

} catch (SAXException e) {
e.printStackTrace();

} catch (Throwable t) {
t.printStackTrace();
}
return maxuserid;

}

Hind
02-21-2006, 05:57 PM
Try this:
add:
int maxuserid = 0;
int newmaxuserid = 0;

Replace:
maxleaveid = Integer.parseInt(maxi);
with:
newmaxleaveid = Integer.parseInt(maxi);
if(newmaxleaveid > maxleaveid )
maxleaveid = newmaxleaveid ;

Good Luck
Hind