Ebben a fejezetben megtanulhatod hogyan ellenőrizhető az XML formázottsága a DOM interfész segítségével. Egy jól formázott XML dokumentumnak követnie kell az XML szintaxis szabályait.
A program leírása:
A program ellenőrzi egy XML dokumentum jól-formázottságát. Ha az XML dokumentum jól formázott, akkor jó, ellenkező esetben hiba üzenetet kell adnia a programnak. A megvalósításhoz a parser() metódus által dobott kivételt használd fel.
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, DOMParserCheck.java:
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class DOMParserCheck {
static public void main(String[] arg){
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()) {
try {
// Create a new factory to create parsers
DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
// Use the factory to create a parser (builder) and use
// it to parse the document.
DocumentBuilder builder = dBF.newDocumentBuilder();
// builder.setErrorHandler(new MyErrorHandler());
InputSource is = new InputSource(xmlFile);
Document doc = builder.parse(is);
System.out.println(xmlFile + " is well-formed!");
}
catch (Exception e) {
System.out.println(xmlFile + " isn't well-formed!");
System.exit(1);
}
}
else {
System.out.print("File not found!");
}
}
catch(IOException io) {
io.printStackTrace();
}
}
}
A következő fejezetben egy elemet keresünk adott XML dokumentumban.