javaxml

How I can get all values from particular tag in XML?


I have file.xml i need extract with java all values from <command> tag:

<?xml version="1.0"?>
<config>
<command> com1 </command>
<result> res1 </result>
<command> com2 </command>
<result> res2 </result>
</config>

May be it exists some methods to extract this values to ArrayList?


Solution

  • XPATH is a good option. Please check below code, it could help you

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder =  factory.newDocumentBuilder();
        Document doc = builder.parse("test.xml");
    
        XPathFactory xFactory = XPathFactory.newInstance();
        XPath xpath = xFactory.newXPath();
        XPathExpression  expr = xpath.compile("//command/text()");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
    
        NodeList nodes = (NodeList) result;
        for (int i=0; i<nodes.getLength();i++){
          System.out.println(nodes.item(i).getNodeValue());
        }