Ebben a fejezetben meg fogod tanulni megszámolni az elemeket egy XML fájlban DOM API segítségével.
A program leírása:
A program segít megszámolni az XML elemeket. A program a konzolon keresztül bekéri az XML fájl nevét és ellenőrzi az elérhetőségét. Elemzi az XML dokumentumot a parse() metódussal. Az XML dokumentum elemzése után bekéri az elem nevét amit meg akarunk számolni. Készíts egy NodeList-et és használd a getElementByTagName() metódust. A getLength() metódus megszámolja a megadott elem előfordulását. Ha a megadott elem nem létezik 0-val térjen vissza.
A minta XML fájl, Employee-Detail.xml:
<?xml version = "1.0" ?>
<Employee-Detail>
<Employee>
<Emp_Id>E-001</Emp_Id>
<Emp_Name>Vinod</Emp_Name>
<Emp_E-mail>Vinod1@yahoo.com</Emp_E-mail>
</Employee>
<Employee>
<Emp_Id>E-002</Emp_Id>
<Emp_Name>Amit</Emp_Name>
<Emp_E-mail>Amit2@yahoo.com</Emp_E-mail>
</Employee>
<Employee>
<Emp_Id>E-003</Emp_Id>
<Emp_Name>Deepak</Emp_Name>
<Emp_E-mail>Deepak3@yahoo.com</Emp_E-mail>
</Employee>
</Employee-Detail>
A program, DOMCountElement.java:
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class DOMCountElement {
public static void main(String[] args) {
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter File name: ");
String xmlFile = bf.readLine();
File file = new File(xmlFile);
if (file.exists()) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Create the builder and parse the fájl
Document doc = factory.newDocumentBuilder().parse(xmlFile);
System.out.print("Enter element name: ");
String element = bf.readLine();
NodeList nodes = doc.getElementsByTagName(element);
System.out.println("xml Document Contains " + nodes.getLength() + " elements.");
}
else{
System.out.print("File not found!");
}
}
catch (Exception ex) {
System.out.println(ex);
}
}
}
A következő fejezetben az XML fájlban lévő elemek számolásával fogunk foglalkozni …