This question relates to recursion. Consider the program shown below (not my real code, but this explains the problem I have).
The function must use recursion as shown, and what I want to do is have a way that each leaf value instead of getting printed out, is saved to a list. So finally I get a List<String> that when I print out gives me the contents of each leaf node.
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<title text=\"title1\">\n" +
" <comment id=\"comment1\">\n" +
" <data> abcd </data>\n" +
" <data> efgh </data>\n" +
" </comment>\n" +
" <comment id=\"comment2\">\n" +
" <data> ijkl </data>\n" +
" <data> mnop </data>\n" +
" <data> qrst </data>\n" +
" </comment>\n" +
"</title>\n";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
List<String> results = traverse(doc.getFirstChild());
//Want to print out results list here...
public static List<String> traverse(Node node){
System.out.println(node.getNodeName());
for(int i = 0; i < node.getChildNodes().getLength(); i++){
traverse(node.getChildNodes().item(i));
}
return null;
}
So my question is, how can I re-write the traverse function in a way that, it still uses recursion but saves all leaf nodes to the list. And then it returns the list of all values.