In: Computer Science
3. Write a Java program that loads a gallery.xml file, determines the number of photos (should be only 3) in it and prints out the number of photos in the gallery.
gallery.xml
<?xml version = "1.0" ?>
<gallery>
<photo id="1">
<name>Image One</name>
<size unit="KB">500</size>
</photo>
<photo id="2">
<name>Image Two</name>
<size unit="KB">587</size>
</photo>
<photo id="3">
<name>Image Three</name>
<size unit="KB">452</size>
</photo>
</gallery>
Main.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
class Main{
public static void main(String[] args) throws IOException {
String inputFile = "gallery.xml";
try {
// Reads text from a character-input stream
BufferedReader reader = new BufferedReader(new InputStreamReader(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);
// Returns a NodeList of all the Elements in document order with a given tag name (photo) and are contained in the document.
NodeList nodes = doc.getElementsByTagName("photo");
System.out.println("\nTotal # of Photos in gallery => " + nodes.getLength() + "\n");
} catch (Exception e) {
System.out.println(e);
}
}
}
Output: