Retrieving child Node value based on Parent Node attribute using DOM parser

Viewed 387

I have XML content as below

<PARENT1 ATTR="FILE1">
  <TITLE>test1.pdf</TITLE>
</PARENT1>
<PARENT2 ATTR="FILE2">
  <TITLE>test2.pdf</TITLE>
</PARENT2>

I want to create a hashmap in Java by adding map Key as Parent attribute value and map Value as Child Node Value. Example:

map.put("FILE1","test1.pdf");
map.put("FILE2","test2.pdf");

I know to get all child nodes list, but i am not getting how to get child node value based on parent node attribute or parent node. How to achieve this in Java using DOM or SAX parser.

Any help is greatly appreciated.

Regards,

Tendulkar

1 Answers

If the XML files aren't huge, I'd recommend using JDOM instead of the default DOM parser as it's much more user friendly.

Here's an example to kinda do what you want, but you'll need to do the error checking and such yourself.

 public class XmlParser {
     private static final String xml = "<parents><parent name=\"name1\"><title>title1</title></parent><parent name=\"name2\"><title>title2</title></parent></parents>";

     public static final void main(String [] args) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xml)));
        Node parents = doc.getChildNodes().item(0);
        Map<String, String> dataMap = new HashMap<>();
    
        for (int i = 0; i < parents.getChildNodes().getLength(); i++) {
            Node parent = parents.getChildNodes().item(i);
            String name = parent.getAttributes().getNamedItem("name").getNodeValue();           
            String title = parent.getChildNodes().item(0).getTextContent();
            dataMap.put(name, title);
        }

        System.out.println(dataMap);
    }
}
Related