Im解析XML文件。我的XML處理程序,我的對象包含數組的Arraylist,以及運行一切並打印它的主類。問題是,每次向陣列列表中添加一個數組時,它都會將之前添加的所有數組更改爲與當前數組相同。我認爲這只是一個靜態的問題,但是一旦我從靜態的東西中解脫出來,它仍然在做同樣的事情。請幫助,我需要儘快完成。ArrayList的數組保持覆蓋我以前的陣列與最新的陣列被添加
這裏是我的處理程序:
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLHandler extends DefaultHandler {
public int counter = 0;
public String[] part = new String[4];
Boolean currentElement = false;
String currentValue = null;
public SitesList sitesList = null; /this used to be static
public SitesList getSitesList() { //this used to be static
return sitesList;
}
public void setSitesList(SitesList sitesList) { //this used to be static
MyXMLHandler handle = new MyXMLHandler(); //thats why the object
handle.sitesList = sitesList;
}
/**
* Called when tag starts (ex:- <name>text</name> -- <name>)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("string-array")) {
/** Start */
String attr = attributes.getValue("name");
sitesList = new SitesList(attr);
}
}
/**
* Called when tag closing (ex:- <name>text</name> -- </name>)
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (counter == 4) {
sitesList.addPart(part);
counter = 0;
}
if (localName.equalsIgnoreCase("item")) {
part[counter] = currentValue;
counter++;
}
currentValue = "";
}
/**
* Called to get tag characters (ex:- <name>text</name> -- to get
* text Character)
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
這裏是我的SitesList對象
import java.util.ArrayList;
/** Contains getter and setter method for varialbles */
public class SitesList {
/** Variables */
private ArrayList<String[]> part = new ArrayList<String[]>();
/**
* In Setter method default it will return arraylist change that to add
*/
public SitesList(String c) {
String[] comp = new String[1];
comp[0] = c;
part.add(comp);
// company name is part(0)[0]
}
public String getCompany() {
return this.part.get(0)[0];
}
public ArrayList<String[]> getPart() {
return part;
}
public void addPart(String[] name) {
part.add(name);
}
public String getName(int i) {
return this.part.get(i)[0];
}
public String getComp1(int i) {
return this.part.get(i)[1];
}
public String getComp2(int i) {
return this.part.get(i)[2];
}
public String getComp3(int i) {
return this.part.get(i)[3];
}
public int getSize() {
return this.part.size();
}
}
這是一個SO問題太多代碼。請將其降低到展示問題所需的最低限度(請閱讀http://sscce.org)。 – 2011-12-28 16:27:24
對不起,第一次大聲笑,只是確保有足夠的信息來解決。 – chartle7 2011-12-28 16:37:46
一個等價的問題已被問及很多次。 – 2011-12-28 16:49:35