我对 XML 序列化和处理完全陌生。我正在做一个项目,我有一堆需要读取和反序列化为对象的 XML 文件。由于我以前从未处理过 XML 文件,因此我尝试在 stackoverflow 上阅读此处并想出了一些代码。有些有效,有些无效,我不明白为什么。
我的 XML 文件看起来像这样(有更多动作,但你明白了):
<MovementCards>
<MovementCard>
<movements>
<int>3</int>
<int>3</int>
<int>2</int>
<int>2</int>
<int>2</int>
<int>2</int>
</movements>
</MovementCard>
</MovementCards>
这些是我的课程:
@XmlRootElement(name="MovementCards")
public class MovementCards {
private List<MovementCard> movementCards;
@XmlElement(name="MovementCard")
public List<MovementCard> getMovementCards() {
return this.movementCards;
}
public void setMovementCards(List<MovementCard> movementCards) {
this.movementCards = movementCards;
}
}
public class MovementCard extends Card {
@XmlElement(name="movements")
private int[] movements = new int[FamilyGameManager.NUMBER_OF_TRACKS];
public int[] getMovements() {
return movements.clone();
}
public void setMovements(int[] movements) {
this.movements = movements;
}
}
最后这是我写的函数:
public List<MovementCard> generateMovementCards() {
List<MovementCard> list = new ArrayList<MovementCard>();
try {
File file = new File(MovementCardsFile);
JAXBContext jaxbContext = JAXBContext.newInstance(MovementCards.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
MovementCards movementCards = (MovementCards) jaxbUnmarshaller.unmarshal(file);
list = movementCards.getMovementCards();
}
catch (JAXBException e) {
e.printStackTrace();
}
return list;
}
提前致谢。