Java XML: get nested element -
i'm programming simple java game , wanted save player data xml encoded save file. i'm discovering java xml dom api , have short question.
suppose have following xml file (doesn't make sense know, example)
<?xml version="1.0"?> <savedgame> <name></name> <player> <name>you</name> <map> <health>2000</health> <name>map_test.map</name> <position> <x>0</x> <y>0</y> </position> </map> <stats> <health>1000</health> <xp> <melee></melee> <magic></magic> <ranged></ranged> <agility></agility> </xp> </stats> <items> <item id="0"> <amount></amount> </item> </items> </player> </savedgame> now want players health level (note there other health element in map section). can done following code:
string hp = ((element) ((element) savedgamedocument.getelementsbytagname("player").item(0)).getelementsbytagname("stats").item(0)).getelementsbytagname("health").item(0).gettextcontent() it works, yes. looks nasty me. usual way getting nested elements? , why isn't there elementlist class? have cast every node.
thanks in advance, jori.
if lot, can let simple serializer handle this. write objects , read objects (like player etc), serializer takes care of xml part. while focus on game development.
as of manually parsing xml dom, logic using can't made smaller anymore. because, dom provides very basic methods of navigation : listing child nodes , picking 1 of them, repeat until reach required node. may lightweight xml, turns nightmare when have parse intricate structures many tag levels.
another faster way streaming, still, more complicated xml structure gets , parser code.
xpath great if need query xml particular node. if need full xml objects transforms, use serializer.
Comments
Post a Comment