Sign in to follow this  
stein102

[LibGdx] Parsing XML

Recommended Posts

I'm pretty new to XML, and I need to use some for a game I'm writing. I need to parse an XML file into game objects. For LibGdx, the XML documentation isn't great, so any tips or code examples would be awesome.

<items>
	<item id="1" name="sword">
		<description text="Just a regular sword."/>
		<wieldable slot="HAND"/>
		<weapon damage = "3"/>
	</item>
</items>

What I need to do is, for each "item":

create an in-game Item object

set id and name to the proper values

Loop through the remaining elements and add each one as a component for that item with the arguments as properties.

 

Any suggestions?

Thanks

Share this post


Link to post
Share on other sites

Something like:

 

// Warning: totally untested. This is just what I would do looking at the code from:
// https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/utils/XmlReader.java
XmlReader reader = new XmlReader();
Element root = reader.parse(inputXmlString);
Array<Element> items = root.getChildrenByName("item");
for (Element child : items)
{
    String description = child.getChildByName("description").getAttribute("text");
    String wieldable = child.getChildByName("wieldable").getAttribute("slot");
    String weapon = child.getChildByName("weapon").getAttribute("damage");
    // do what you wish with these
}

Share this post


Link to post
Share on other sites

Any ideas?

I said inputXmlString, not pathToXmlFile. It's thinking the string you're passing it is the XML (not the path to an XML file).

 

You should look at the other parse() methods. There are ones that take a ReaderInputStream, or a FileHandle. Use the appropriate one.

Share this post


Link to post
Share on other sites

 

Any ideas?

I said inputXmlString, not pathToXmlFile. It's thinking the string you're passing it is the XML (not the path to an XML file).

 

You should look at the other parse() methods. There are ones that take a ReaderInputStream, or a FileHandle. Use the appropriate one.

 

 

That makes more sense, the Parse(FileHandle) Method worked perfectly. Thank you.

 

Also, is there any way to see all of the elements inside of <item>?

Share this post


Link to post
Share on other sites

I've got it figured out.

		//Loop through each "Item"
		for (Element child : items){
			//Loop through each Item's components
			int numberOfChildren = child.getChildCount();
			Array<Element> components = new Array<Element>();
			for(int i = 0; i < numberOfChildren; i++){
				components.add(child.getChild(i));
			}
		}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this