• Advertisement
Sign in to follow this  

[java] using XML

This topic is 4714 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I can't figure out how to save data to xml in my game (I have found some tutorials how to load data from xml and there is some info about it in sun java's sdk, but i can't find anything about saving data to xml). Maybe someone could post some code or give me some pointers?

Share this post


Link to post
Share on other sites
Advertisement
Kris-XK,

You can always use OpenSource software like TinyXML. But if you want to write your own, simply take your loader and reverse it. If you get some problems, just post them.

-brad

Share this post


Link to post
Share on other sites
I can't use TinyXML or other third party libs. And I don't want (I'm too lazy) to reinvent the wheel and write my own code for xml loading / saving.

I load xml like this:


DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse( new File("data/docs/hiscores.xml") );


So I'm just using some objects from java's standard libs, so it's rather hard to reverse it :). There is class WebRowSet, but it has something to do with sql, so I don't think that it's good way to solve this problem.

Share this post


Link to post
Share on other sites
If you don't want to use any third party libs, You're making your job much more difficult than it has to be :)

The classes you're interested in are javax.xml.Transform , and javax.xml.transform.stream.StreamResult.

Haven't done this in a while (about 2 years !) , but off the top of my head, something like this ought to work:

target is your OutputStream, document your Document.

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(target));

D.



Share this post


Link to post
Share on other sites
You're just writing out text, what's wrong write just writing the XML elements directly to file?

After you parse the XML when loading, you still have to go through and extract the data from the Document. So when saving, instead of inserting an element into some equivalent document and then writing out the document, just write the XML directly to the file. The only thing that might make life a little more difficult is nice formatting (which really isn't that hard).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement