将项目保存到XML文件中 [英] Saving a project into an XML file

查看:110
本文介绍了将项目保存到XML文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Netbeans在java中编写一个游戏。



我想在每轮开始时将游戏保存到XML文件,并且能够在游戏开始时加载任何保存的游戏。



XML文件最终应包含当前保存的游戏状态(玩家,姓名,金额等)。



我阅读了互联网,并了解到,我需要使用DOM创建游戏所有类的内容树,然后使用JAXB将该树组织成一个XML文件。



我不知道从哪里开始,如何创建上下文树等等。



任何帮助或好的教程将会有所帮助(找不到任何好的东西)。

解决方案

JAXB使您能够轻松地将Java对象的实例转换为/从XML转换。使用JAXB,您将永远不需要直接与DOM进行交互。

  JAXBContext jc = JAXBContext.newInstance(Game.class); 

文件文件=新文件(gameData.xml);

Unmarshaller unmarshaller = jc.createUnmarshaller();
游戏游戏=(游戏)unmarshaller.unmarshal(文件);

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
marshaller.marshal(游戏,文件);

JAXB是通过异常的配置,这意味着您只需要注释您的模型,使您的XML表示不同从默认。以下内容将帮助您开始:




I'm writing a game in java using Netbeans.

I want to be able to save the game to an XML file in the beginning of each round, and to be able to load any saved game in the beginning of the game.

The XML file should eventually include the current state of the game when saved (players, names, sum of money, etc.).

I read over the internet and understood that I need to create a content tree of all the classes of the game using DOM and then Marshall the tree into an XML file, using JAXB.

I have no idea where to start from, how to create the context tree, and so on.

Any help or good tutorial would be helpful (couldn't find anything good).

解决方案

JAXB enables you to easily convert instances of Java objects to/from XML. With JAXB you will never need to interact directly with DOM.

JAXBContext jc = JAXBContext.newInstance(Game.class);

File file = new File("gameData.xml");

Unmarshaller unmarshaller = jc.createUnmarshaller();
Game game = (Game) unmarshaller.unmarshal(file);

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(game, file);

JAXB is configuration by exception meaning you only need to annotate your model where you wan the XML representation to differ from the default. The following will help you get started:

这篇关于将项目保存到XML文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆