[LibGdx] Parsing XML

Started by
5 comments, last by stein102 10 years, 7 months ago

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

Advertisement

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
}
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

I'm getting an error on


root = reader.parse("items/Items.xml");

Exception in thread "LWJGL Application" com.badlogic.gdx.utils.SerializationException: Error parsing XML on line 1 near: items/Items.xml

Any ideas?

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 Reader, InputStream, or a FileHandle. Use the appropriate one.

[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

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 Reader, InputStream, 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>?

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));
			}
		}

This topic is closed to new replies.

Advertisement