'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
Solution 1:[1]
The values 100 and 200 are in Textnodes. You can get the content with:
laptopElement.getTextContent()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ralf Renz |
