Validación de documentos XML  

Posted by Danny in , ,

Veamos cómo se valida un documento XML.


import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.DefaultHandler;

public class Validate {

public Validate(String filename) {
StringBuffer buff = new StringBuffer();

try {
File f = new File(".", filename);
StringBuffer errorBuff = new StringBuffer();
InputSource input = new InputSource(new FileInputStream(f));

// Set systemID so parser can find the dtd with a relative URL in the source document.
input.setSystemId(f.toString());
SAXParserFactory spfact = SAXParserFactory.newInstance();

spfact.setValidating(true);
spfact.setNamespaceAware(true);

SAXParser parser = spfact.newSAXParser();
XMLReader reader = parser.getXMLReader();

//Instantiate inner-class error and lexical handler.
Handler handler = new Handler(filename, errorBuff);
reader.setProperty("
http://xml.org/sax/properties/lexical-handler ", handler);
parser.parse(input, handler);

if (handler.containsDTD && !handler.errorOrWarning) { // valid
buff.append("VALID " + filename +"\n");
}
else if (handler.containsDTD) { // not valid
buff.append ("NOT VALID " + filename + "\n");
buff.append(errorBuff.toString());
}
else buff.append("NO DOCTYPE DECLARATION " + filename + "\n");
}
catch (Exception e) {
buff.append("NOT WELL-FORMED " + filename + ". " + e.getMessage() + "\n");
}

System.out.print(buff.toString());
}

class Handler extends DefaultHandler implements LexicalHandler {
boolean errorOrWarning;
boolean containsDTD;
String sourceFile;
StringBuffer errorBuff;

Handler(String sourceFile, StringBuffer errorBuff) {
super();
this.sourceFile = sourceFile;
this.errorBuff = errorBuff;
errorOrWarning = false;
containsDTD = false;
}

public void error(SAXParseException exc) {
errorBuff.append(sourceFile + " Error: " + exc.getMessage()+ "\n");
errorOrWarning = true;
}

public void warning(SAXParseException exc) {
errorBuff.append(sourceFile + " Warning:" + exc.getMessage()+ "\n");
errorOrWarning = true;
}

public void startDTD (String name, String publicId, String systemId) throws SAXException {
containsDTD = true;
}

public void endDTD () throws SAXException {}
public void startEntity (String name) throws SAXException {}
public void endEntity (String name) throws SAXException {}
public void startCDATA () throws SAXException {}
public void endCDATA () throws SAXException {}
public void comment (char ch[], int start, int length) throws SAXException {}
}

public static void main(String[] args) {
Validate v = new Validate("birds.xml");
}
}

Entradas relacionadas:

0 comentarios

Publicar un comentario

BlogESfera Directorio de Blogs Hispanos - Agrega tu Blog

Archives