如何使用dom解析器java在xml中解析相同的名称标签?

如何使用dom解析器java在xml中解析相同的名称标记?

我有以下xml文件,我想使用java中的dom解析器进行解析。

   1  cards notes dice  50 50 10 60 offices   2  notes dice cards  10 10 10 security room   

 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 } 

但我宁愿建议使用XPath

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("/GameWorld/player"); NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);