parse xml using dom java

前端 未结 3 2000
青春惊慌失措
青春惊慌失措 2021-01-25 20:15

I have the bellow xml:


    
        
            wish
             


        
3条回答
  •  萌比男神i
    2021-01-25 20:39

    If you do not want to use the if statement you can use XPath to get the element you need directly.

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("source.xml");
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("/*/listOfDocs/documents/document/topic");
    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getAttributes().getNamedItem("id"));
        System.out.println(nodes.item(i).getAttributes().getNamedItem("percentage"));
    }
    

    Please check GitHub project here.

    Hope this helps.

提交回复
热议问题