Skip to content

Instantly share code, notes, and snippets.

@vignarajj
Created January 29, 2019 08:07
Show Gist options
  • Save vignarajj/6f269c4a21f5775c6e25caff41fe13a2 to your computer and use it in GitHub Desktop.
Save vignarajj/6f269c4a21f5775c6e25caff41fe13a2 to your computer and use it in GitHub Desktop.
Implement a function FolderNames, which accepts a string containing an XML file that specifies folder structure and returns all folder names that start with startingLetter.
package javaproblems;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class Folders {
public static Collection<String> folderNames(String xml, char startingLetter) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
NodeList node = doc.getElementsByTagName("folder");
Collection<String> result = new ArrayList<String>();
for (int i = 0; i < node.getLength(); i++) {
String nodeName = node.item(i).getAttributes().getNamedItem("name").getNodeValue();
if (nodeName.toCharArray()[0] == startingLetter) {
result.add(nodeName);
}
}
return result;
}
public static void main(String[] args) throws Exception {
String xml
= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<folder name=\"c\">"
+ "<folder name=\"program files\">"
+ "<folder name=\"uninstall information\" />"
+ "</folder>"
+ "<folder name=\"users\" />"
+ "</folder>";
Collection<String> names = folderNames(xml, 'u');
for (String name : names) {
System.out.println(name);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment