Just want to read and write xml data

Hi there,



I searched and tried myself a lot but i haven’t been able to find an answer. This is probably a very easy one :shame: … but well i’m sitting here with a problem. I just want to read simple xml files like this:



[xml]

<resource>

<name>Money</name>

</resource>

[/xml]



Then in game, i want to be able to read it and create an new Resource() object from it.



Because i wanted to do this the clean way, i tried to mess around with the assetManager. Do i need to create a new Loader?

The files are xml but the extensions are going to be .res files.



You probably going to ask me why i want to do this… i want the game to be -easy- modifiable so users can create their own resources (with rules and parameters later).

This is a pretty straight-forward Java question. You can read/write XML in two basic ways: by loading the entire structure into memory or by ‘streaming’ and going over data as it hits your parser. If the files are relatively small, loading the entire structure (known as DOM) is pretty easy.



http://java.sun.com/developer/codesamples/xml.html

oops, there’s also the loader part. Yes, you’d implement a new AssetLoader :slight_smile:

This is my personal XML loader (as AssetLoader) relying on JDOM:



[java]

package X;



import java.io.IOException;

import org.jdom.JDOMException;

import org.jdom.input.SAXBuilder;

import com.jme3.asset.AssetInfo;

import com.jme3.asset.AssetLoader;



public class XMLLoader implements AssetLoader {

@Override

public Object load(AssetInfo assetInfo) throws IOException {

SAXBuilder builder = new SAXBuilder();

try {

return builder.build(assetInfo.openStream()).getRootElement();

} catch(JDOMException ex) {

throw new IOException(ex);

}

}

}

[/java]

1 Like

Thanks guys! This little example was where i was looking for! :slight_smile:

I prefer xstream, it allows you to xmlerilise any object and can restore them from xml, also its pretty fast.

Use Groovy!!! It makes xml parsing super easy.

Scala has some language features regarding xml too but I don’t think this helps the OP…

If you want to use xml pull parsing, Nifty comes with the xpp3 library so it’s already included in the jME distribution libraries.

Wow all those libraries :stuck_out_tongue: Thanks guys but now i can’t choose :stuck_out_tongue: so many

I would also check out JAXB.