Search code examples
javaxmlhashtablerft

XML to Hashtable


Currently I have the code below to put the data in a Hash. My question: which value do i have to put in the part of !!!SOMETHING!!!. The code only has to read one elementtag and insert it's value in the hashtable.

public void ReadXML(){
    try {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(fileout);
        doc.getDocumentElement().normalize();
        Hashtable hash = new Hashtable();

        NodeList dataNodes = doc.getElementsByTagName("DataArea");
//      getChildNodes().item(0).getChildNodes();
        Element root = doc.getDocumentElement();
        String dataNodeIndex = root.toString();
        System.out.println("");

    for (int dataNodeIndex1 = 0; dataNodeIndex1 < dataNodes.getLength(); dataNodeIndex1++)
        {
            Node nodeName = dataNodes.item(dataNodeIndex1);

            if (nodeName.getNodeType() == Node.ELEMENT_NODE) {
                Element elementName = (Element) nodeName;
                NodeList elementNameList = elementName.getElementsByTagName(elementtag1);
                Element elementName2 = (Element) elementNameList.item(0);
                NodeList nameElement = elementName2.getChildNodes();
                System.out.println("NodeContent: "  + ((Node) nameElement.item(0)).getNodeValue());

            }
            hash.put(elementtag1, !!!SOMETHING!!!);

            System.out.println(hash);
        }       


    }



    catch(Exception e){ 
        e.printStackTrace();
    }


}

Solution

  • You should use these method that i found :

    protected String getString(String tagName, Element element) {
        NodeList list = element.getElementsByTagName(tagName);
        if (list != null && list.getLength() > 0) {
            NodeList subList = list.item(0).getChildNodes();
    
            if (subList != null && subList.getLength() > 0) {
                return subList.item(0).getNodeValue();
            }
        }
    
        return null;
    }
    

    use it like this :

    if (NodeName.getNodeType() == Node.ELEMENT_NODE) {
        Element ElementName = (Element) NodeName;
        Hash.put(Elementtag1, getString(Elementtag1, ElementName));
    
    }
    

    Check it out :

    http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/

    and

    How to retrieve element value of XML using Java?