我正在寫一個解析關於停車場的xml提要的android應用程序。 我創建了一個單獨的類,它以字符串的形式接收xml提要,然後該類將解析字符串,爲在提要中找到的每個停車場創建對象。每次我刷新xml提要並且需要解析它時,我都會使用它,應該讓這個類是否爲靜態的。什麼時候做出靜態的事情我還沒有100%確定。我應該讓這個方法是靜態的嗎?
我的代碼:
public class XMLParser2 {
private static CarPark carPark;
private static ArrayList<CarPark> carParkListings;
// Parse XML string and save each car park object created within an Arraylist collection
public static ArrayList<CarPark> parseXML(String xml) throws XmlPullParserException, IOException {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(xml));
int eventType = xpp.getEventType();
carParkListings = new ArrayList<CarPark>();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("situation")) {
// Create new CarPark object to hold car park data
carPark = new CarPark();
}
// Check start tag for each element wanting to obtain and save in the
// carPark object using its associated set method
if (xpp.getName().equalsIgnoreCase("carparkstatus")) {
String status = xpp.nextText();
if (status.matches("enoughSpacesAvailable"))
carPark.setCarParkActive("Open");
else if (status.matches("carParkClosed"))
carPark.setCarParkActive("Closed");
else
carPark.setCarParkActive("Full");
}
if (xpp.getName().equalsIgnoreCase("overallstarttime")) {
carPark.setDateCreated(xpp.nextText());
}
if (xpp.getName().equalsIgnoreCase("latitude")) {
Double latitude = Double.parseDouble(xpp.nextText());
carPark.setLatitude(latitude);
}
if (xpp.getName().equalsIgnoreCase("longitude")) {
Double longitude = Double.parseDouble(xpp.nextText());
carPark.setLongtitude(longitude);
}
if (xpp.getName().equalsIgnoreCase("carparkidentity")) {
String[] identity = xpp.nextText().split("\\:");
carPark.setCarParkName(identity[0]);
carPark.setCarParkID(identity[1]);
}
if (xpp.getName().equalsIgnoreCase("occupiedspaces")) {
int occupiedSpaces = Integer.parseInt(xpp.nextText());
carPark.setOccupiedSpaces(occupiedSpaces);
}
if (xpp.getName().equalsIgnoreCase("totalcapacity")) {
int totalCapacity = Integer.parseInt(xpp.nextText());
carPark.setTotalSpaces(totalCapacity);
}
}
// Check if the tag is an end tag
else if (eventType == XmlPullParser.END_TAG) {
if (xpp.getName().equalsIgnoreCase("situation")) {
// Calculate total spaces free
carPark.setFreeSpaces();
// Add CarPark class object to carParkListings ArrayList collection
carParkListings.add(carPark);
}
}
// Move to next event
eventType = xpp.next();
}
// Return ArrayList collection
return carParkListings;
}
}
在你說的方法題目和問題類中,你是指哪一個?如果你的意思是類,這可能有助於http://stackoverflow.com/q/7486012/612920 – Mansuro
嘗試發佈你的問題在這裏:http://codereview.stackexchange.com/ – dit