How to parse same name tag in xml using dom parser java?

前端 未结 1 1822
不思量自难忘°
不思量自难忘° 2021-01-25 00:00

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.

&         


        
相关标签:
1条回答
  • 2021-01-25 00:34
    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);
    
    0 讨论(0)
提交回复
热议问题