我有一个xml文件,如下所示
<Moves>
<Move name="left">
<Coord X="100" Y="100"/>
<Coord X="50" Y="100"/>
</Move>
<Move name="right">
<Coord X="10" Y="80"/>
<Coord X="40" Y="90"/>
</Move>
<Moves> 我正在使用SAX解析器在Java中解析它。以下两个方法基本上解析了它
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("Coord")){
X = Integer.parseInt(attributes.getValue("X"));
Y = Integer.parseInt(attributes.getValue("Y"));
} else if (qName.equalsIgnoreCase("Move")) {
move_points.clear();
move_name = attributes.getValue("name");
}
}
/* If the read element is Move, add a MoveList with the name and if it is
* a Coord, create a Point with it.
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("Coord")){
move_points.add(new Points(X, Y));
} else if (qName.equalsIgnoreCase("Move")) {
moves_list.add(new MovesList(move_name, move_points));
}
}我有一个存储读取的所有坐标的ArrayList move_points和一个存储移动名称及其坐标的Arraylist moves_list (这里是一个arraylist - move_points )
我遇到的问题是,在解析文档时,moves_list中的所有元素都具有正确的名称,但是move_points中的条目或存储的coord是XML文件中最后一次移动的条目。
当我检查在每个元素移动后在endElement方法中输入到moves_list中的内容时,它显示了输入到moves_list中的正确坐标,但是当解析整个文档并且在解析根元素移动之后查看moves_list中的内容时,我得到的是具有最后一次移动的所有坐标的moves_list。
请帮帮我。
PS。moves_list是一个公共静态变量
MovesList类
public class MovesList {
private ArrayList<Points> move_points;
private String move_name;
public MovesList (String move_name, ArrayList<Points> move_points) {
this.move_name = move_name;
this.move_points = move_points;
}
public String getName(){
return move_name;
}
public ArrayList<Points> getPoints(){
return move_points;
}}
Points类
public class Points extends Point {
private int X;
private int Y;
public Points (int X, int Y) {
this.X = X;
this.Y = Y;
}
public Points (Points p) {
X = p.getIntX();
Y = p.getIntY();
}
public int getIntX () {
return X;
}
public int getIntY () {
return Y;
}
}发布于 2012-07-28 09:36:11
我认为你的问题在于你没有创建一个新的move_points对象。所以这就是:
} else if (qName.equalsIgnoreCase("Move")) {
move_points.clear();
move_name = attributes.getValue("name");
}应该是这样:
} else if (qName.equalsIgnoreCase("Move")) {
move_points = new ArrayList<Points>(); // note difference
move_name = attributes.getValue("name");
}否则,每个MovesList对象都将有一个引用同一对象的move_points变量。
发布于 2012-07-28 09:04:54
您有一个名为move_points的变量,当您创建新的MovesList时,您将使用一个名为points的变量。是打字错误吗?此外,由于您似乎在开始新的Move元素时共享了move_points并将其清除,因此我希望您在创建MovesList时正在复制列表。
https://stackoverflow.com/questions/11697314
复制相似问题