[java] using XML

Started by
3 comments, last by joanusdmentia 19 years ago
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?
--KriS
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
-brad
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.
--KriS
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.



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).
"Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of Fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose, so let me simply add that it's my very good honor to meet you and you may call me V.".....V

This topic is closed to new replies.

Advertisement