gpt4 book ai didi

java - XML 未按预期在 Java 中解析

转载 作者:行者123 更新时间:2023-11-29 05:57:01 25 4
gpt4 key购买 nike

我有一个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(这里是一个数组列表 - move_points)

我遇到的问题是,当文档被解析时,moves_list 中的所有元素都具有正确的名称,但 move_points 中的条目或存储的坐标是 XML 文件中最后一步的元素。

当我在每个元素 Move 之后检查在 endElement 方法中输入到 moves_list 的内容时,它显示了正确的坐标被输入到 moves_list 但是当整个文档被解析并且我在根元素 Moves 之后查看 moves_list 中的内容时已被解析,我得到了 moves_list,其中包含最后一步的所有坐标。

请帮帮我。

附言。 moves_list 是一个公共(public)静态变量

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;
}

积分等级

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;
}

}

最佳答案

我认为你的问题是你没有创建一个新的 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 变量。

关于java - XML 未按预期在 Java 中解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11697314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com