Note that there are some explanatory texts on larger screens.

plurals
  1. POConvert .XML to HashMap
    primarykey
    data
    text
    <p>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 ...</p> <h2>This is the .xml file:</h2> <pre><code>&lt;RelationShipTypes&gt; &lt;RelationShipType key="1" name="Organization Unit"/&gt; &lt;RelationShipType key="2" name="Employee"/&gt; &lt;RelationShipType key="3" name="Customer"/&gt; &lt;RelationShipType key="4" name="Supplier"/&gt; &lt;RelationShipType key="5" name="Agency"/&gt; &lt;RelationShipType key="6" name="Partner"/&gt; &lt;RelationShipType key="7" name="SALES AGENT"/&gt; &lt;RelationShipType key="8" name="End User"/&gt; &lt;RelationShipType key="9" name="Other"/&gt; &lt;/RelationShipTypes&gt; </code></pre> <h2>This is the code:</h2> <pre><code> public static Map&lt;String, String&gt; 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&lt;String, String&gt; createMap(Node node) { Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); NodeList nodeList = node.getChildNodes(); for (int i = 0; i &lt; nodeList.getLength(); i++) { Node currentNode = nodeList.item(i); if (currentNode.hasAttributes()) { for (int j = 0; j &lt; currentNode.getAttributes().getLength(); j++) { Node item = currentNode.getAttributes().item(i); map.put(item.getNodeName(), item.getTextContent()); } } if (node.getFirstChild() != null &amp;&amp; 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></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload