asif kaif
asif kaif

Reputation: 159

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

Upvotes: 0

Views: 867

Answers (1)

Ralf Renz
Ralf Renz

Reputation: 1061

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

laptopElement.getTextContent()

Upvotes: 1

Related Questions