packagecom.crunchify;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjavax.xml.parsers.DocumentBuilderFactory;
importorg.w3c.dom.Document;
importorg.w3c.dom.NodeList;
/**
* @author Crunchify.com
*/
publicclassCrunchifyCountXMLElements{
publicstaticvoidmain(String[]args)throwsIOException{
StringinputFile=“https://cdn.crunchify.com/wp-content/uploads/code/Company.xml”;
try{
// Reads text from a character-input stream
BufferedReader reader=newBufferedReader(newInputStreamReader(System.in));
// Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
// The Document interface represents the entire HTML or XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document’s data.
Document doc=factory.newDocumentBuilder().parse(inputFile);
// Get input element from user
System.out.print(“Enter element name: “);
Stringelement=reader.readLine();
// Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.
NodeList nodes=doc.getElementsByTagName(element);
System.out.println(“nHere you go => Total # of Elements: “+nodes.getLength());
}catch(Exceptione){
System.out.println(e);
}
}
}