Hey there,
I am just a little confused with the code below, i parse the XML file although i cant call functions from outside the main. My programming isnt really up to scratch. Ive had a long break so now im paying for it :(

Any help/ suggestions would be very grateful!

package Util;
ALL IMPORTS DONE BY ECLIPSE

public class XMLreader{	

	public static void main(String argv[]){
		try{	
			File file = new File("c:\\Programming Garmin Files\\2009-01-26-09-00-09.tcx");
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(file);
			doc.getDocumentElement().normalize();
			System.out.println("Root element: " + doc.getDocumentElement().getNodeName() + "\n");
			NodeList nodeLst = doc.getElementsByTagName("Trackpoint");
			
			//this works but i wish to call the functions from outside this class
			readLatitude(nodeLst, 5);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public static float readLatitude(NodeList nodeLst, int index){
		float latArr[] = new float[nodeLst.getLength()];
		try{
			for(int i=0; i<nodeLst.getLength(); i++){
				Node fstNode = nodeLst.item(i);
				if(fstNode.getNodeType() == Node.ELEMENT_NODE){
					Element fstElmnt =(Element)fstNode;
					
					NodeList latiElmntLst = fstElmnt.getElementsByTagName("LatitudeDegrees");
				    Element latiElmnt = (Element) latiElmntLst.item(0);
			    	NodeList latitude = latiElmnt.getChildNodes();
			    	latArr[i] = Float.valueOf(latitude.item(0).getNodeValue().trim()).floatValue();
			    	System.out.println("Latitude Degrees :"+ latArr[i]);
				}
			}
		}catch(NullPointerException e){
			e.printStackTrace();
		}
		//System.out.println(latArr[index]);
		return latArr[index];
	}
	public static float readLongitude(NodeList nodeLst, int index){
		float longArr[] = new float[nodeLst.getLength()];
		for(int i=0; i<nodeLst.getLength(); i++){
			Node fstNode = nodeLst.item(i);
			if(fstNode.getNodeType() == Node.ELEMENT_NODE){
				Element fstElmnt =(Element)fstNode;
				
				NodeList longElmntLst = fstElmnt.getElementsByTagName("LongitudeDegrees");
		    	Element longElmnt = (Element) longElmntLst.item(0);
		    	NodeList longitude = longElmnt.getChildNodes();
		    	longArr[i] = Float.valueOf(longitude.item(0).getNodeValue().trim()).floatValue();
		    	//System.out.println("Longitude Degrees :"+ longArr[i]);
			}
		}
		return longArr[index];
	}
	
	public static float readAltitude(NodeList nodeLst, int index){
		float altArr[] = new float[nodeLst.getLength()];
		try{
			for(int i=0; i<nodeLst.getLength(); i++){
				Node fstNode = nodeLst.item(i);
				if(fstNode.getNodeType() == Node.ELEMENT_NODE){
					Element fstElmnt =(Element)fstNode;
					
					NodeList altElmntLst = fstElmnt.getElementsByTagName("LongitudeDegrees");
			    	Element altElmnt = (Element) altElmntLst.item(0);
			    	NodeList altitude = altElmnt.getChildNodes();
			    	altArr[i] = Float.valueOf(altitude.item(0).getNodeValue().trim()).floatValue();
			    	//System.out.println("Altitude Degrees :"+ altArr[i]);
				}
			}
		}catch(NullPointerException e){
			e.printStackTrace();
		}
		return altArr[index];
	}

	public static void readDate(NodeList nodeLst){
		for(int i= 0; i<nodeLst.getLength(); i++){
			Node fstNode = nodeLst.item(i);			
			if(fstNode.getNodeType() == Node.ELEMENT_NODE){
				Element fstElmnt =(Element)fstNode;
				
				NodeList dateElmntLst = fstElmnt.getElementsByTagName("Time");
		    	Element dateElmnt = (Element) dateElmntLst.item(0);
		    	NodeList date = dateElmnt.getChildNodes();
		    	
		    	//System.out.println("Time :"+((Node)date.item(0)).getNodeValue().trim());
		    	String dateStr = ((Node)date.item(0)).getNodeValue().trim().toString();
		    	String temp[]; temp = dateStr.split("T");
		   		System.out.println("Date: " + temp[0] + "    Time: " + temp[1]);
			}
		}
	}
	
	public static void readDistance(NodeList nodeLst){
		for(int i= 0; i<nodeLst.getLength(); i++){
			Node fstNode = nodeLst.item(i);			
			if(fstNode.getNodeType() == Node.ELEMENT_NODE){
				Element fstElmnt =(Element)fstNode;
				
				NodeList distElmntLst = fstElmnt.getElementsByTagName("DistanceMeters");
		    	Element distElmnt = (Element) distElmntLst.item(0);
		    	NodeList distance = distElmnt.getChildNodes();
		    	float fDistance = Float.valueOf(distance.item(0).getNodeValue().trim()).floatValue();
		    	System.out.println("Distance(meters) :"+ fDistance);
			}
		}
	}
	
	public float getLongitude(int index){
		return readLongitude(nodeLst, index);
	}
	public float getLatitude(int index){
		return readLatitude(nodeLst, index);
	}
	public float getAltitude(int index){
		return readAltitude(nodeLst, index);
	}
	
	
	
}

thanks again!

You call a public static method from outside the class by using itsclass name and method name, eg
XMLreader.readLatitude(...)

You call a public static method from outside the class by using itsclass name and method name, eg
XMLreader.readLatitude(...)

Oh, what i meant was the functions down below aren't recognizing the nodelist made in the main. So it requires a null variable to be initialized.

public float getDistance(int index){
		return XMLreader.readAltitude(nodeLst, index);
	}

brings up this error.

- nodeLst cannot be resolved

Thankyou for your response :D

OK, misunderstood Q. Sorry.
Can't see why you're passing nodeLst around like that. It's set up during initialisation, and then accessed by all the methods, so why not make it a variable at the class level and let all the methods access it directly? In that case all you need to pass in the index you want.
ps: You may be getting into problems mixing static and non-static in this code. It looks like you are getting the XML data from a file, then providing access to results calculated from it. Maybe you should make all the code non-static, and just instantiate an instance for each data file - move your code from main(...) to a new constructor that takes the file as a parameter: public XMLreader(File file) { etc } then create it from the main method:

public static void main(String argv[]){
  XMLReader reader =   new XMLreader(new File("...");
  reader.readAltitude(index)...
}

Thanks James!
You have totally changed my perspective on how i designed the class! Very thankful for that. Now i am stuck with another error :(

When i run the function in the main, the functions list the values although theyre stopped by a NullPointerException.

double altitude = Double.parseDouble(altList.item(0).getTextContent());

seems to be the problem, i think it is the way i am gathering the values or the way i am converting the values.
Here is the new revamped code :D

package gps;

import java.io.File;
import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.List;

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

import model.Activity;
import model.Author;
import model.Creator;
import model.Lap;
import model.Position;
import model.TrackPoint;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLReader{
	public static void main(String[] args) throws Exception{
		String inFile = "c:\\Programming Garmin Files\\2009-01-26-09-00-09.tcx";
XMLReader reader = new XMLReader();



//reader.posReader(inFile);
	reader.trackReader(inFile);
	
	reader.lapReader(inFile);
	reader.creatorReader(inFile);
	reader.authorReader(inFile);
	reader.activityReader(inFile);
}


public Position[] posReader(String inFile) throws Exception{
	File file = new File(inFile);
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	Document doc = db.parse(file);
	doc.getDocumentElement().normalize();
	System.out.println("Root element: " + doc.getDocumentElement().getNodeName() + "\n");
NodeList nodeLst = doc.getElementsByTagName("Trackpoint");

Position[] position = new Position[nodeLst.getLength()];
for(int i= 0; i<nodeLst.getLength(); i++){
	Node fstNode = nodeLst.item(i);			
	if(fstNode.getNodeType() == Node.ELEMENT_NODE){
		Element fstElmnt =(Element)fstNode;
		NodeList latList = fstElmnt.getElementsByTagName("LatitudeDegrees");
double latitude = Double.parseDouble(latList.item(0).getTextContent());
NodeList longList = fstElmnt.getElementsByTagName("LongitudeDegrees");
double longitude = Double.parseDouble(longList.item(0).getTextContent());

//TEST
/*
System.out.println("BLOCK---------------------");
System.out.println("Latitude: " + latitude);
System.out.println("Longitude: " + longitude);
*/
			position[i] = new Position(latitude, longitude);
		}
	}
	return position;		
}
public TrackPoint[] trackReader(String inFile) throws ParserConfigurationException, SAXException, IOException{
	File file = new File(inFile);
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	Document doc = db.parse(file);
	doc.getDocumentElement().normalize();
	System.out.println("Root element: " + doc.getDocumentElement().getNodeName() + "\n");
NodeList nodeLst = doc.getElementsByTagName("Trackpoint");

TrackPoint[] trackpoint = new TrackPoint[nodeLst.getLength()];
for(int i= 0; i<nodeLst.getLength(); i++){
	Node fstNode = nodeLst.item(i);			
	if(fstNode.getNodeType() == Node.ELEMENT_NODE){
		Element fstElmnt =(Element)fstNode;
		//String time = fstNode.getFirstChild().getTextContent();
GregorianCalendar timeDate = new GregorianCalendar();
NodeList altList = fstElmnt.getElementsByTagName("AltitudeMeters"); 
double altitude = Double.parseDouble(altList.item(0).getTextContent());
NodeList distList = fstElmnt.getElementsByTagName("DistanceMeters");
double distance = Double.parseDouble(distList.item(0).getTextContent());

//TEST
/*
System.out.println("BLOCK---------------------");
System.out.println("Altitude: " + altitude);
System.out.println("Distance: " + distance);
*/
			
			trackpoint[i] = new TrackPoint(timeDate, null, altitude, distance);
		}
	}
	return trackpoint;		
}
public Lap[] lapReader(String inFile) throws ParserConfigurationException, SAXException, IOException{
	File file = new File(inFile);
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	Document doc = db.parse(file);
	doc.getDocumentElement().normalize();
	System.out.println("Root element: " + doc.getDocumentElement().getNodeName() + "\n");
NodeList nodeLst = doc.getElementsByTagName("Activity");

Lap[] lap = new Lap[nodeLst.getLength()];
for(int i= 0; i<nodeLst.getLength(); i++){
	Node fstNode = nodeLst.item(i);			
	if(fstNode.getNodeType() == Node.ELEMENT_NODE){
		Element fstElmnt =(Element)fstNode;
		//String time = fstNode.getFirstChild().getTextContent();
GregorianCalendar timeDate = new GregorianCalendar();
NodeList ttsList = fstElmnt.getElementsByTagName("TotalTimeSeconds"); 
double totaltime = Double.parseDouble(ttsList.item(0).getTextContent());
NodeList distList = fstElmnt.getElementsByTagName("DistanceMeters");
double distance = Double.parseDouble(distList.item(0).getTextContent());
NodeList maxList = fstElmnt.getElementsByTagName("MaximumSpeed");
double maxSpeed = Double.parseDouble(maxList.item(0).getTextContent());
NodeList calList = fstElmnt.getElementsByTagName("Calories");
double calories = Double.parseDouble(calList.item(0).getTextContent());
NodeList intList = fstElmnt.getElementsByTagName("Intensity");
String intensity = intList.item(0).getTextContent();
NodeList cadList = fstElmnt.getElementsByTagName("Cadence");
int cadence = Integer.parseInt(cadList.item(0).getTextContent());
NodeList trigList = fstElmnt.getElementsByTagName("TriggerMethod");
String triggerMethod = trigList.item(0).getTextContent();

//TEST
/*
System.out.println("BLOCK---------------------");
System.out.println("TotalTime: " + totaltime);
System.out.println("Distance: " + distance);
System.out.println("Max Speed: " + maxSpeed);
System.out.println("Calories: " + calories);
System.out.println("Intensity: " + intensity);
System.out.println("Cadence: " + cadence);
System.out.println("Trigger Method: " + triggerMethod);
*/
			lap[i] = new Lap(timeDate, totaltime, distance, maxSpeed, calories, intensity, cadence, triggerMethod);
		}
	}
	return lap;
}
public Creator[] creatorReader(String inFile) throws ParserConfigurationException, SAXException, IOException{
	File file = new File(inFile);
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	Document doc = db.parse(file);
	doc.getDocumentElement().normalize();
	System.out.println("Root element: " + doc.getDocumentElement().getNodeName() + "\n");
NodeList nodeLst = doc.getElementsByTagName("Activity");

Creator[] creator = new Creator[nodeLst.getLength()];
for(int i= 0; i<nodeLst.getLength(); i++){
	Node fstNode = nodeLst.item(i);			
	if(fstNode.getNodeType() == Node.ELEMENT_NODE){
		Element fstElmnt =(Element)fstNode;
		//String time = fstNode.getFirstChild().getTextContent();
NodeList nameList = fstElmnt.getElementsByTagName("Name"); 
String name = nameList.item(0).getTextContent();
NodeList unitList = fstElmnt.getElementsByTagName("UnitId");
String unitId = unitList.item(0).getTextContent();
NodeList prodList = fstElmnt.getElementsByTagName("ProductID");
int prodId = Integer.parseInt(prodList.item(0).getTextContent());
NodeList versList = fstElmnt.getElementsByTagName("VersionMajor");
String version = versList.item(0).getTextContent();

//TEST
/*
System.out.println("BLOCK---------------------");
System.out.println("Product Name: " + name);
System.out.println("UnitID: " + unitId);
System.out.println("ProductID: " + prodId);
System.out.println("Version(major): " + version);
*/
			
			creator[i] = new Creator(name, unitId, prodId, version);
		}
	}
	return creator;
}

public Author[] authorReader(String inFile) throws ParserConfigurationException, SAXException, IOException{
	File file = new File(inFile);
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	Document doc = db.parse(file);
	doc.getDocumentElement().normalize();
	System.out.println("Root element: " + doc.getDocumentElement().getNodeName() + "\n");
NodeList nodeLst = doc.getElementsByTagName("Author");

Author[] author = new Author[nodeLst.getLength()];
for(int i= 0; i<nodeLst.getLength(); i++){
	Node fstNode = nodeLst.item(i);			
	if(fstNode.getNodeType() == Node.ELEMENT_NODE){
		Element fstElmnt =(Element)fstNode;
		NodeList nameList = fstElmnt.getElementsByTagName("Name"); 
String name = nameList.item(0).getTextContent();
NodeList bversList = fstElmnt.getElementsByTagName("VersionMajor"); 
String bvers = bversList.item(0).getTextContent();
NodeList typeList = fstElmnt.getElementsByTagName("Type"); 
String type = typeList.item(0).getTextContent();
NodeList langList = fstElmnt.getElementsByTagName("LangID"); 
String langID = langList.item(0).getTextContent();
NodeList partList = fstElmnt.getElementsByTagName("PartNumber"); 
String partNum = partList.item(0).getTextContent();

//TEST
/*
System.out.println("BLOCK---------------------");
System.out.println("Name: " + name);
System.out.println("Version: " + bvers);
System.out.println("Type: " + type);
System.out.println("LangID: " + langID);
System.out.println("Part Number: " + partNum);
*/
			
			author[i] = new Author(name, bvers, type, langID, partNum);
		}
	}
	return author;
}
public Activity[] activityReader(String inFile) throws ParserConfigurationException, SAXException, IOException{
	File file = new File(inFile);
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	Document doc = db.parse(file);
	doc.getDocumentElement().normalize();
	System.out.println("Root element: " + doc.getDocumentElement().getNodeName() + "\n");
NodeList nodeLst = doc.getElementsByTagName("Activities");
NodeList nodeLst2 = doc.getElementsByTagName("Creator");
Activity[] activity = new Activity[nodeLst.getLength()];
List<Lap> laps = null;

for(int i= 0; i<nodeLst.getLength(); i++){
	Node fstNode = nodeLst.item(i);			
	if(fstNode.getNodeType() == Node.ELEMENT_NODE){
		Element fstElmnt =(Element)fstNode;
		String sport = fstNode.getFirstChild().getNodeName();
		NodeList idList = fstElmnt.getElementsByTagName("Id"); 
String Id = idList.item(0).getTextContent();

//creator
for(int j=0; j<nodeLst.getLength(); j++){
	Node scndNode = nodeLst2.item(i);			
	if(scndNode.getNodeType() == Node.ELEMENT_NODE){
		NodeList nameList = fstElmnt.getElementsByTagName("Name"); 
	String name = nameList.item(0).getTextContent();
	NodeList unitList = fstElmnt.getElementsByTagName("UnitId");
	String unitId = unitList.item(0).getTextContent();
	NodeList prodList = fstElmnt.getElementsByTagName("ProductID");
	int prodId = Integer.parseInt(prodList.item(0).getTextContent());
	NodeList versList = fstElmnt.getElementsByTagName("VersionMajor");
	String version = versList.item(0).getTextContent();
	
	activity[i] = new Activity(sport, Id, laps, new Creator(name, unitId, prodId, version));
	
	//TEST
	/*
	System.out.println("BLOCK---------------------");
	System.out.println("Sport: " + sport);
	System.out.println("ID: " + Id);
	System.out.println("Name: " + name);
	System.out.println("UnitID: " + unitId);
	System.out.println("ProductID: " + prodId);
	System.out.println("Version(major): " + version);
	*/
					}
				}
				
			}
		}
		return activity;
	}
}

Also, if the XML tags are

<Activities>
		<Activity Sport="Biking">

How do i get the Sport value? i tried getAttributes although it doesnt work :(

And if it helps, here is the XML file. Thank you everyone for your consideration :D

I believe you should be able to cast the Node to an Element and use Element.getAttribute(java.lang.String)
(Just guessing though - we use JDOM here instead of that api)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.