私は次のクラスを持っています:
package com.somedir.someotherdir;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
public class SchemaValidator
{
private static Logger _logger = Logger.getLogger(SchemaValidator.class.getName());
/**
* @param file - the relative path to and the name of the XML file to be validated
* @return true if validation succeeded, false otherwise
*/
public final static boolean validateXML(String file)
{
try
{
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema();
Validator validator = schema.newValidator();
validator.validate(new StreamSource(file));
return true;
}
catch (Exception e)
{
_logger.log(Level.WARNING, "SchemaValidator: failed validating " + file + ". Reason: " + e.getMessage(), e);
return false;
}
}
}
schema.newValidator("dir/to/schema.xsd")
やっぱり使うべきなのか、それとも現在のバージョンでいいのか知りたいのですが?DoSの脆弱性があることを読みましたが、誰かがそれについてもっと情報を提供できるかもしれませんか?また、パスは絶対パスである必要がありますか、それとも相対パスである必要がありますか?
検証されるXMLのほとんどはそれぞれ独自のXSDを持っているので、XML自体に記載されているスキーマを読みたいと思います(xs:noNamespaceSchemaLocation="schemaname.xsd"
)。
検証は、起動時または手動リロード(サーバーソフトウェア)中にのみ実行されます。