Convert .XML to HashMap

pupil

New Member
I have .xml file like this. i want convert this file to HashMap and reverse in Java. Could you please tell me how can i convert it to HashMap file? Thank you ...This is the .xml file:\[code\]<RelationShipTypes> <RelationShipType key="1" name="Organization Unit"/> <RelationShipType key="2" name="Employee"/> <RelationShipType key="3" name="Customer"/> <RelationShipType key="4" name="Supplier"/> <RelationShipType key="5" name="Agency"/> <RelationShipType key="6" name="Partner"/> <RelationShipType key="7" name="SALES AGENT"/> <RelationShipType key="8" name="End User"/> <RelationShipType key="9" name="Other"/> </RelationShipTypes>\[/code\]This is the code:\[code\] public static Map<String, String> convertNodesFromXml(String xml) throws SAXException, IOException, ParserConfigurationException { try { InputStream is = new ByteArrayInputStream(xml.getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(is); return createMap(document.getDocumentElement()); } catch (SAXException ex) { Logger.getLogger(BaseDataLoader.class.getName()).log(Level.SEVERE, null, ex); throw ex; } catch (IOException ex) { Logger.getLogger(BaseDataLoader.class.getName()).log(Level.SEVERE, null, ex); throw ex; } catch (ParserConfigurationException ex) { Logger.getLogger(BaseDataLoader.class.getName()).log(Level.SEVERE, null, ex); throw ex; } } public static Map<String, String> createMap(Node node) { Map<String, String> map = new HashMap<String, String>(); NodeList nodeList = node.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node currentNode = nodeList.item(i); if (currentNode.hasAttributes()) { for (int j = 0; j < currentNode.getAttributes().getLength(); j++) { Node item = currentNode.getAttributes().item(i); map.put(item.getNodeName(), item.getTextContent()); } } if (node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.ELEMENT_NODE) { map.putAll(createMap(currentNode)); } else if (node.getFirstChild().getNodeType() == Node.TEXT_NODE) { map.put(node.getLocalName(), node.getTextContent()); } } return map; }\[/code\]
 
Top