我想针对外部XSD描述验证XML文件。这是从我的XSD
创建的Schema
obejct
private static Schema xmlSchema;
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
String FEATURE= "";
// forbid DOCTYPE
FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
factory.setFeature(FEATURE, true);
xmlSchema = factory.newSchema(new File(XML_XSD_SCHEME));
} catch (Exception e) {
}
另外,我创建了validateXMLSchema
静态方法,负责验证XML文件:
public static boolean validateXMLSchema(String xmlPath) {
if (xmlSchema == null) {
return false;
}
InputStream inputStream = null;
try {
URL xmlFileURL = new File(xmlPath).toURI().toURL();
inputStream = xmlFileURL.openStream();
SAXSource saxSource = new SAXSource(new InputSource(inputStream));
Validator validator = xmlSchema.newValidator();
String FEATURE ="";
// disallow DOCTYPE
FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
validator.setFeature(FEATURE, true);
//forbid external Entity
FEATURE ="http://xml.org/sax/features/external-general-entities";
validator.setFeature(FEATURE, false);
//forbid external parameters
FEATURE ="http://xml.org/sax/features/external-parameter-entities";
validator.setFeature(FEATURE, false);
validator.validate(saxSource);
} catch (Exception e) {
return false;
} finally {
try {
inputStream.close();
} catch (IOException e) {
}
}
return true;
}
问题是,即使我在我的XML文件<!DOCTYPE foo [<!ELEMENT foo ANY ><!ENTITY......
中添加了外部实体定义,
validateXMLSchema
方法返回true
。
有人可以帮帮我吗?
答案 0 :(得分:2)
我猜你想要将这些功能应用于读取XML文档的SAX解析器。尝试创建新的XMLReader
并在将SAXSource
传递给Validator
之前明确配置它:
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
XMLReader reader = spf.newSAXParser().getXMLReader();
String FEATURE ="";
// disallow DOCTYPE
FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
reader.setFeature(FEATURE, true);
//forbid external Entity
FEATURE ="http://xml.org/sax/features/external-general-entities";
reader.setFeature(FEATURE, false);
//forbid external parameters
FEATURE ="http://xml.org/sax/features/external-parameter-entities";
reader.setFeature(FEATURE, false);
SAXSource saxSource = new SAXSource(reader, new InputSource(inputStream));
Validator validator = xmlSchema.newValidator();
validator.validate(saxSource);