1

How do you parse the same name tag in xml using dom parser java?

I have the following xml file that I would like to parse using the dom parser in java.

<?xml version="1.0"?>
    <GameWorld>
        <player>
            <playerID>1</playerID>
            <inventory>
                <item>cards</item>
                <item>notes</item>
                <item>dice</item>
            </inventory>
            <position>50 50 10 60</position>
            <room>offices</room>
        </player>
        <player>
            <playerID>2</playerID>
            <inventory>
                <item>notes</item>
                <item>dice</item>
                <item>cards</item>
            </inventory>
            <position>10 10 10</position>
            <room>security room</room>
        </player>
    </GameWorld>
Ishan
  • 3,931
  • 11
  • 37
  • 59
  • [Possibly Duplicate](http://stackoverflow.com/questions/11863038/how-to-get-the-attribute-value-of-an-xml-node-using-java/11863333#11863333) – thar45 Oct 15 '12 at 04:27
  • If anyone can solve this : http://stackoverflow.com/questions/17421506/how-to-parse-same-tag-name-in-android-xml-dom-parsing – Altair Jul 02 '13 at 16:40

1 Answers1

2
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
Element root = doc.getDocumentElement();
NodeList nodeList = doc.getElementsByTagName("player");
for (int i = 0; i < nodeList.getLength(); i++) {
  Node node = nodeList.item(i);
  // do your stuff
}

but I'd rather suggest to use XPath

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/GameWorld/player");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
jdevelop
  • 12,176
  • 10
  • 56
  • 112