Skip to content

Instantly share code, notes, and snippets.

@tgvdinesh
Created February 6, 2017 10:46
Show Gist options
  • Save tgvdinesh/1a4a6d8d5b37094ccb7ea5ce1047c5b0 to your computer and use it in GitHub Desktop.
Save tgvdinesh/1a4a6d8d5b37094ccb7ea5ce1047c5b0 to your computer and use it in GitHub Desktop.
Recursively looks for a node name and prints specified attribute value
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Paths;
public class XMLParser {
public static void main(String[] args) throws Exception {
if(args == null) throw new Exception("File name is required as argument");
String fileName = args[0];
try {
String xmlString = new String(Files.readAllBytes(Paths.get(fileName)));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
NodeList nl = document.getDocumentElement().getChildNodes();
for (int k = 0; k < nl.getLength(); k++) {
printTags(nl.item(k));
}
} catch (ParserConfigurationException | IOException | SAXException e) {
e.printStackTrace();
}
}
private static void printTags(Node nodes) {
if (nodes.hasChildNodes() || nodes.getNodeType() != 3) {
if (nodes.getNodeName().equalsIgnoreCase("Criteria")) {
if (nodes.getAttributes().getNamedItem("Name").getNodeValue().equalsIgnoreCase("emp.id")) {
System.out.println(nodes.getAttributes().getNamedItem("Value").getNodeValue());
}
}
NodeList nl = nodes.getChildNodes();
for (int j = 0; j < nl.getLength(); j++) printTags(nl.item(j));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment