Skip to content
Advertisement

get key value Pairs from XML file in Java

I have to get Key and values from XMl File, I am getting Key but not value


       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       
            DocumentBuilder builder = factory.newDocumentBuilder();

          
            Document document = builder.parse(new File("laptops.xml"));

            
            document.getDocumentElement().normalize();

             NodeList laptopList = document.getElementsByTagName("string");

            for(int i = 0; i <laptopList.getLength(); i++) {
                Node laptop = laptopList.item(i);
                if(laptop.getNodeType() == Node.ELEMENT_NODE) {

                    Element laptopElement = (Element) laptop;
                    System.out.println(laptopElement.getAttribute("name"));
           }
        }

XML File:

<laptops>
   <string name="usb">100</string>
   <string name="charger">200</string>
</laptops


Result Should be Like this : usb: 100,

charger: 200

Advertisement

Answer

The values 100 and 200 are in Textnodes. You can get the content with:

laptopElement.getTextContent()

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement