我有一个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 Parser在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)
我遇到的问题是,在解析文档时,move_list中的所有元素都具有正确的名称,但move_points中的条目或存储的coord是XML文件中最后一次移动的条目。
当我在每个元素Move之后检查endElement方法中输入的actions_list的内容时,它会显示正确的coord被输入到moves_list中,但是当解析整个文档时我查看根元素Moves之后的moves_list内部的内容已被解析,我得到的move_list与最后一步的所有坐标一起。
请帮帮我。
PS。 moves_list是一个公共静态变量
MovesList Class
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;
}
}
积分等级
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;
}
}
答案 0 :(得分:2)
我认为您的问题是您没有创建新的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变量,该变量引用同一个对象。
答案 1 :(得分:1)
你有一个名为move_points的变量,当你创建一个新的MovesList时,你使用一个名为points的变量。这是一个错字吗?此外,由于您似乎在启动新的Move元素时共享move_points并清除它,我希望您在创建MovesList时复制List。